Making a C function pointer work with C-style stack based calling mechanics in C++

mani8899's Avatar, Join Date: May 2011
Newbie Member
I want to call a pure C style function from a dll in my C++ program. I tried casting my function pointer using reinterpret_cast to __cdecl and still the calling convention of _stdcall seems to be preserved. I am new to Windows C++ programming.

This is my C++ call
Code:
reinterpret_cast< Error ( __cdecl*)(int,int)> (GetProcAddress(Mydll::GetInstance()->ReturnDLLInstance(), "add"))(1,10)
actual function in the dll is

Code:
Error __cdecl add(int,int);
Debugger throws me the error run time check failure #0. I am working in Windows-C++. Also I am exporting functions from my dll and I dont have access to my C files.
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Usually to call C from C++ you just need to extern "C" the prototype:
Code:
extern "C"
{
Error add(int,int);
}
Then the compiler knows not to mangle the name and not to look for a mangled name.
mani8899's Avatar, Join Date: May 2011
Newbie Member
Thanks! But what if I cannot work with the C code.I just have it as a dll. In that case is there a work around??
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
extern "C" is C++ code, not C code. This is what you put in the C++ code to make it call the function in the DLL. You still need a prototype, and you extern "C" it to stop the compiler mangling the names, then the linker resolves the call.