Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can random C++ 2011 standard functions be called from a C routine?

Tags:

c++

c

random

c++11

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);
like image 989
nopeva Avatar asked Dec 16 '25 14:12

nopeva


2 Answers

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.

like image 160
vbar Avatar answered Dec 19 '25 04:12

vbar


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"?

like image 25
Alex Avatar answered Dec 19 '25 02:12

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!