-2

I have a struct defined in Managed.h and I would like to be able to use it inside a different project, which is unmanaged C++ (let's call it Unmanaged.h).

I tried referencing the dll, a few different #includes, but I couldn't make it work. Is there a simple way to do this ?

For information : I am quite new to C++ programming (I do C# usually), and I use Visual Studio 2015.

Olivier Giniaux
  • 870
  • 2
  • 8
  • 22

1 Answers1

1

It would be useful to see some code and the error message that you are seeing. But as a basic example:

  1. CLR file containing the struct. Call it MyStruct.h:

using namespace System;

namespace ManagedNameSpace {

    public value struct MyStruct {
        void f() {
            System::Console::WriteLine("test");
        }
    };
}
  1. The unmanaged class includes the CLR struct and as an explicit example I have called the object in the constructor but you can easily move this to an implementation file (Remember to include the file in the header):

#include "MyStruct.h"

class UnManagedClass {
    public:
        explicit UnManagedClass() {
            ManagedNameSpace::MyStruct clrObj;
            clrObj.f();
            std::cout << "This compiles fine";
        }
};

Take note that certain CLR types require marshalling. For example String will need to be marshalled. Here is an example of converting a string to LPCWSTR

LPCWSTR lpcwStr = (LPCWSTR)(Marshal::StringToHGlobalUni(clrString)).ToPointer() 
IsakBosman
  • 1,453
  • 12
  • 19