Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Making a C function pointer work with C-style stack based calling mechanics in C++ (http://www.go4expert.com/forums/c-function-pointer-c-style-stack-based-t25878/)

mani8899 24May2011 05:06

Making a C function pointer work with C-style stack based calling mechanics in C++
 
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 24May2011 12:09

Re: Making a C function pointer work with C-style stack based calling mechanics in C+
 
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 24May2011 21:59

Re: Making a C function pointer work with C-style stack based calling mechanics in C+
 
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 25May2011 04:42

Re: Making a C function pointer work with C-style stack based calling mechanics in C+
 
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.


All times are GMT +5.5. The time now is 08:54.