Including headers from an unmanaged C++ code inside C++/CLI code

青春壹個敷衍的年華 提交于 2019-11-29 18:02:01

Linker errors are a different kettle of fish from compiler errors. You forgot to document the exact linker errors you see, but a very common mishap when you compile code with /clr in effect is that the default calling convention for non-C++ member function changes. The default is __clrcall, a convention that's optimized for managed code. While functions compiled without /clr defaults to __cdecl. Which changes the way the function name is mangled. You see this back in the linker error message, is shows that it is looking for a __clrcall function and can't find it.

You'll need to either explicitly declare your functions in the .h file with __cdecl. Or tell the compiler that these functions are not managed code. Which is the best way to tackle it:

#pragma managed(push, off)
#include "unmanagedHeader.h"
#pragma managed(pop)

Solution was fairly simple:

  1. I added both unmanaged and managed projects to a single solution in Visual Studio.
  2. Set the unmanaged project's "Configuration Type" to "Static Library" (.lib).
  3. Right click on the managed project -> References -> Add Reference -> Projects -> -> Add Reference.
  4. Then in my managed class, I include the header.h (only) just like I did in my question.
  5. Compiled successfully!

Thank you

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!