Reputation: 1200
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.
Edit Code from comment
reinterpret_cast< Error ( __cdecl*)(int,int)> (GetProcAddress(Mydll::GetInstance()->ReturnDLLInstance(), "add"))(1,10)
is my call. The actual function syntax seems to have been declared as
Error __cdecl add(int,int);
Debugger throws me the error run time check failure #0. I am working in Windows-C++
Upvotes: 3
Views: 612
Reputation: 1200
This helped me out!
http://www.codeguru.com/forum/archive/index.php/t-70673.html
Upvotes: 0
Reputation: 28902
There are two things at work over here.
The first is the calling convention. The calling convention is a part of the Application Binary Interface (ABI) that decides whether the caller or the callee is responsible for cleaning up the stack. If you want your functions to behave correctly both you harness and your dll will need to use the same calling convention. In WIN32 APIs this is typically __stdcall although C typically uses __cdecl.
The other issue is name mangling. Since the arguments of a function form part of the function signature in C++ (to allow for function overloading) this information is incorporated into the symbol table of you object code. This will typically be a whole bunch of extra strange characters. C does not need to do name mangling since it does not allow function overloading.
Sometimes in C++ you want to call C functions (ie C function symbols compiled by a C and not a C++ compiler). In such a case you need to define the function in an extern "C" {}
block.
Hopefully this will help you out
Upvotes: 3
Reputation: 239
Usually you need to use extern "C" for this...
--- c_code.h ---
void func(int arg);
void (*func_ptr)(int arg);
--- cpp_code.cpp ---
extern "C" void func(int arg);
extern "C" void (*func_ptr)(int arg);
int main()
{
func(20);
*func_ptr(20);
}
Upvotes: 6
Reputation: 1502
I believe the solution to your question is 'extern "C" { ...'
See http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.3
Upvotes: 8