I need to generate a random integer from a range and have found very interesting what is discussed here in the answer by @Walter. However, it is C++11 standard and I need to use C, is there a way of making the call from C? I reproduce his answer here:
#include <random>
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased
auto random_integer = uni(rng);
You cannot use C++ classes in C, but can wrap the C++ functionality in functions, which can be called from C, e.g. in getrandom.cxx:
#include <random>
static std::random_device rd;
static std::mt19937 rng(rd());
static std::uniform_int_distribution<int> uni(min,max);
extern "C" int get_random()
{
return uni(rng);
}
This is a C++ module exporting a get_random function with C linkage (that is, callable from C. You declare it in getrandom.h:
extern "C" int get_random();
and can call it from your C code.
If you want to call C++ code from C code, you can wrap your code in an extern "C" block. The function signature must be a valid C function, and is then available to C code to call. However, the contents of the function can include whatever C++-isms you want.
See this question for more info: In C++ source, what is the effect of extern "C"?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With