Mixing managed and unmanaged C++ code?

假装没事ソ 提交于 2019-12-01 08:03:14

问题


I have a couple specific questions regarding mixing managed C++ with unmanaged C++:

  1. If I leave out ref and value in a class/struct declaration, does that automatically make the class/struct unmanaged? Or do I still need to include the #pragma unmanaged and #pragma managed directives?
  2. How compatible are unmanaged and managed types? For example, I can have an unmanaged object in a managed class, right? Can I pass an unmanaged class/struct to a managed function (ie. pass a std::string to a managed function)?

Thanks for your help,

Alex


回答1:


You can't have hybrid types (native class containing a managed object, or vice versa). What is possible is to have a pointer to a native class inside a managed one, and a managed handle, wrapped with the gcroot template, inside a native class. This is needed to make sure that the garbage collector never tries to move native data around (which would break pointers held by pure native code).

Managed types are always implemented using managed code. Native types must be implemented using managed code if they call to managed types.

#pragma managed(push, off) is the way to force code to be compiled as native. A couple reasons to do this: better optimization from the C++ compiler, can't be interrupted by garbage collection, etc. Alternatively, you can use /clr:pure to force all code to be compiled as managed, or even /clr:safe to do the same thing and also make it verifiable.

Any code that is compiled as managed can accept both native and managed types as arguments and return values. And that code can be inside a managed type, native type, or free (global) function.



来源:https://stackoverflow.com/questions/10729008/mixing-managed-and-unmanaged-c-code

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