I’m trying to create a native wrapper around a .Net library in C++/CLI, so that regular C++ code can consume it. For this example, let’s say this is the C# code I’m trying to wrap:
class Foo
{
public Bar GetBar() {...}
public string SomeProperty { get; set; }
}
class Bar
{
public void Baz() {...}
}
I’m basically trying to do roughly this in C++/CLI (dll project):
class __declspec(dllexport) NativeFoo
{
public:
NativeBar GetBar();
std::string GetName();
void SetName(const std::string &value);
private:
Foo ^m_foo;
};
class __declspec(dllexport) NativeBar
{
friend class NativeFoo;
public:
void Baz();
private:
Bar(Bar ^bar);
Bar ^m_bar;
};
That way, a C++ library could link to this, use NativeFoo as if it’s a regular C++ class. Internally, NativeFoo would convert parameters to pass the implementation over to m_foo, marshal anything managed back into a native representation and return that to its caller…
However, the problem I’m running into is I can’t have managed members of an unmanaged class:
error C3265: cannot declare a managed 'm_bar' in an unmanaged 'NativeFoo'
Similarly I can’t mark NativeFoo as “ref” (being a managed class itself) because then I can’t export it:
C3386: 'NativeFoo' : __declspec(dllexport)/__declspec(dllimport) cannot be applied to a managed type
What’s the right way to use managed pointers in my C++ objects?
You need to use
gcrootto declare a managed handle on an unmanaged type. You need this for any unmanaged type, whether it’s being dllexported or not.There’s a MSDN page on it with some good information & some samples.
I believe you’ll end up with something like this: