39
votes

Title explains. I have native C++ dlls that I'm writing C++/CLI wrappers for, which will in turn will be imported in C# as reference.

The problem is that in C# I don't see the classes I have in wrapper (imported from DLL).

What keywords should I use and HOW to re-declare my native C++ objects to become visible in C#?

1
Are the wrapper classes public? Declaration should be "public ref class { ... };"Asik
I know that. What I'm asking is that is such a thing possible: public ref class wrapper_class = native_class;? Are such approaches possible?Haix64
It's not that simple. The wrapper class would host a native_class object and create wrapper methods for all the methods of native_class that you want to expose. The wrapper methods just marshal the parameters and delegate the call to the native_class object.Asik
Ok, then what's the simplest solution? The one resulting in least overhead or redirected member function calls?Haix64
If you can somehow expose your class functionality as C functions, then you could use P/Invoke. Otherwise, the C++/CLI wrapper is to way to go. See my answer below for an example.Asik

1 Answers

78
votes

Ok, tutorial. You have a C++ class NativeClass that you want to expose to C#.

class NativeClass { 
public:
    void Method();
};

1) Create a C++/CLI project. Link to your C++ library and headers.

2) Create a wrapper class that exposes the methods you want. Example:

#include "NativeClass.h"

public ref class NativeClassWrapper {
    NativeClass* m_nativeClass;

public:
    NativeClassWrapper() { m_nativeClass = new NativeClass(); }
    ~NativeClassWrapper() { this->!NativeClassWrapper(); }
    !NativeClassWrapper() { delete m_nativeClass; }
    void Method() {
        m_nativeClass->Method();
    }
};

3) Add a reference to your C++/CLI project in your C# project.

4) Use the wrapper type within a using statement:

using (var nativeObject = new NativeClassWrapper()) {
    nativeObject.Method();
}

The using statement ensures Dispose() is called, which immediately runs the destructor and destroys the native object. You will otherwise have memory leaks and probably will die horribly (not you, the program). Note : The Dispose() method is magically created for you.