I have a couple specific questions regarding mixing managed C++ with unmanaged C++:
- 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?
- 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
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.