Search code examples
variablesc++-clinativemanaged

C++ Declare managed type in native code


I need to know how do I declare a managed type inside native code?

Like: I have a ref class Editor in Editor.h

In native code(main.cpp):

Editor^ MainEditor;

But it gives me the following:

MainEditor' : global or static variable may not have managed type 'Cube3D::Editor ^'

I've tried to make it inside a container but I still need to declare it.


Solution

  • You can't do that directly. The issue is that the managed object will be moved by the garbage collector, and purely native code can't handle that.

    Here's what is allowed:

    • Members of managed types must be compiled with /clr to produce managed code. This can use both managed and native types implemented with both managed and native code.
    • Members of native types and namespaces can be compiled with /clr to produce managed code. This can use both managed and native types implemented with both managed and native code.
    • Members of native types and namespaces can be compiled without /clr to produce native code. This can use only native types, but the types used can be implemented by either managed or native code.
    • It's even possible for some members of a native type to be implemented in native code and other members of the same type to be implemented in managed code.

    So, you need a layer in between your native code and your managed type, this in-between layer will be a native type implemented with managed code.

    Of course, #pragma managed can be used interchangeably with /clr, for finer control.