使 C 函数指针与 C++ 中基于 C 风格堆栈的调用机制一起工作;
我想从我的 C++ 程序中的 dll 调用纯 C 风格的函数。我尝试使用reinterpret_cast
将函数指针转换为__cdecl
,但_stdcall
的调用约定似乎仍然保留。我是 Windows C++ 编程新手。
编辑评论中的代码
reinterpret_cast< Error ( __cdecl*)(int,int)> (GetProcAddress(Mydll::GetInstance()->ReturnDLLInstance(), "add"))(1,10)
是我的电话。实际的函数语法似乎已被声明为
Error __cdecl add(int,int);
调试器向我抛出错误运行时检查失败#0。我正在 Windows-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.
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++
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我相信您问题的解决方案是 'extern "C" { ...'
请参阅 http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.3
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
通常你需要为此使用 extern "C"...
--- c_code.h ---
--- cpp_code.cpp ---
Usually you need to use extern "C" for this...
--- c_code.h ---
--- cpp_code.cpp ---
这里有两件事在起作用。
第一个是调用约定。调用约定是应用程序二进制接口 (ABI) 的一部分,它决定调用者或被调用者是否负责清理堆栈。如果您希望您的函数能够正确运行,那么您的harness 和您的dll 都需要使用相同的调用约定。在 WIN32 API 中,这通常是 __stdcall,尽管 C 通常使用 __cdecl。
另一个问题是名称修改。由于函数的参数构成了 C++ 中函数签名的一部分(以允许函数重载),因此该信息被合并到目标代码的符号表中。这通常是一大堆额外的奇怪字符。 C 不需要进行名称修改,因为它不允许函数重载。
有时在 C++ 中您想要调用 C 函数(即由 C 而不是 C++ 编译器编译的 C 函数符号)。在这种情况下,您需要在
extern "C" {}
块中定义该函数。希望这能帮助你
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
这帮助了我!
http://www.codeguru.com/forum/archive/index .php/t-70673.html
This helped me out!
http://www.codeguru.com/forum/archive/index.php/t-70673.html