Call a system C++ function from C

Thursday, July 3, 2014

I have a C library, which I'm not really allowed to modify in substantial way, that heavily uses the random function, which is not available on my Visual Studio 2010 compiler (see another one of my questions)


So, I have to write my own random method. I tried to use a simple random() { srand(time(NULL)); return rand(); } but the library main conceptor doesn't like it (he's on Mac and I think he doesn't care much about my problems). He tells me to run srand() only once when the library is run, but since there might be multiple entry points in this lib, I don't know how to do it. If you have a solution to this problem, I'm all ears.


Update: I have found out that the "main" function is always run during the loading of the library (from what I understand), so I'll use this for the seeding. But I'm still interested in the solution to this particular question.


So I decided to follow another method of generating random numbers:



#include <Windows.h>
#include <wincrypt.h>
long int random() {
HCRYPTPROV prov;
if (CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, 0)) {
long int li = 0;
if (CryptGenRandom(prov, sizeof(li), (BYTE *)&li)) {
return li;
} else {
// random number not generated
return 0;
}

if (!CryptReleaseContext(prov, 0)) {
// context not released
return 0;
}
} else {
// context not created
return 0;
}
}


But then I get this kind of error:



error LNK2019: unresolved external symbol __imp__CryptReleaseContext@8 referenced in the function _random



The problem, if I understand correctly, is that I'm calling C++ functions from C, and C doesn't understand the name mangling happening during C++ compilation.


I have visited the classic answer to calling C++ from C, but I didn't see a way to call a system C++ function from a C method. Is there something I've missed?


Thanks!







http://ift.tt/1xlKApu