Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a class defined in a c++ dll in c# code

Tags:

c++

c#

dll

pinvoke

I have a dll that was written in c++, I need to use this dll in my c# code. After searching I found that using P/Invoke would give me access to the function I need, but these functions are defined with in a class and use non-static private member variables. So I need to be able to create an instance of this class to properly use the functions. How can I gain access to this class so that I can create an instance? I have been unable to find a way to do this.

I guess I should note that the c++ dll is not my code.

like image 753
Dan Vogel Avatar asked Nov 24 '08 18:11

Dan Vogel


1 Answers

There is no way to directly use a C++ class in C# code. You can use PInvoke in an indirect fashion to access your type.

The basic pattern is that for every member function in class Foo, create an associated non-member function which calls into the member function.

class Foo { public:   int Bar(); }; extern "C" Foo* Foo_Create() { return new Foo(); } extern "C" int Foo_Bar(Foo* pFoo) { return pFoo->Bar(); } extern "C" void Foo_Delete(Foo* pFoo) { delete pFoo; } 

Now it's a matter of PInvoking these methods into your C# code

[DllImport("Foo.dll")] public static extern IntPtr Foo_Create();  [DllImport("Foo.dll")] public static extern int Foo_Bar(IntPtr value);  [DllImport("Foo.dll")] public static extern void Foo_Delete(IntPtr value); 

The downside is you'll have an awkward IntPtr to pass around but it's a somewhat simple matter to create a C# wrapper class around this pointer to create a more usable model.

Even if you don't own this code, you can create another DLL which wraps the original DLL and provides a small PInvoke layer.

like image 160
JaredPar Avatar answered Sep 21 '22 06:09

JaredPar