Call class member of c++ DLL from c#

1.1k views Asked by At

I already know how to call functions of a C++ DLL from C#, when the provided functions are not members of classes. But how would I call a class member like foo in the following code sample?

class _declspec(dllexport) MyClass{
    public:
        void foo();
};

Doing something like this doesn't work, because the c#-Compiler doesn't know which class to call.

[DllImport("MyDLL", CallingConvention = CallingConvention.Cdecl)]
    private static extern void foo();
1

There are 1 answers

0
Michael Gunter On BEST ANSWER

The only way to directly call methods on a C++ object from C# (and most other languages) is to create a full-fledged COM object out of it.

An easier way with a level of indirection: Develop an API of purely static methods that reflect the object's operations. Then you can call that from .NET easily.

C++:

MyClass* WINAPI CreateMyClass() { return new MyClass(); }
void WINAPI CallFoo(MyClass* o) { o->foo(); }

C#:

[DllImport("MyDLL")]
private static IntPtr CreateMyClass();

[DllImport("MyDLL")]
private static void CallFoo(IntPtr o);