Reputation: 175
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();
Upvotes: 1
Views: 1185
Reputation: 12811
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);
Upvotes: 3