Problem:
Using P/Invoke to access functions in a C DLL with member variables and non-static methods requires creating instances of the defining class. How can access be gained to this class?
Answer:
Directly using a C class in C# is not possible. Instead, follow these steps:
Example:
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; }
In C#:
[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);
Wrapper Class:
To simplify usage, wrap the IntPtr pointer into a C# wrapper class:
public class FooWrapper { private IntPtr _foo; public FooWrapper() { _foo = Foo_Create(); } public int Bar() { return Foo_Bar(_foo); } public void Dispose() { Foo_Delete(_foo); } }
Alternative Approach:
If unable to modify the original DLL, create an intermediate DLL that wraps the original DLL and exposes the wrapped class to C#.
The above is the detailed content of How Can I Access a C DLL Class with Member Variables and Non-Static Methods from C#?. For more information, please follow other related articles on the PHP Chinese website!