问题描述
我有一个用c ++编写的dll,我需要在我的c#代码中使用这个dll。搜索后,我发现使用P / Invoke可以让我访问我需要的功能,但这些函数是在一个类中定义的,并使用非静态的私有成员变量。所以我需要能够创建这个类的一个实例来正确地使用这些功能。我如何获得访问这个类,以便我可以创建一个实例?我一直找不到这样做的办法。我想我应该注意到c ++ dll不是我的代码。
没有办法直接在C#代码中使用C ++类。您可以间接使用PInvoke来访问您的类型。
基本模式是对于Foo类中的每个成员函数,创建一个调用成员函数的关联非成员函数。
class Foo {
public:
int Bar();
};
Foo * Foo_Create(){return new Foo(); }
int Foo_Bar(Foo * pFoo){return pFoo-> Bar(); }
void Foo_Delete(Foo * pFoo){delete pFoo; }
现在这是将这些方法插入到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);
缺点是你会有一个尴尬的IntPtr传递,但创建一个简单的事情一个围绕这个指针的C#包装类来创建一个更可用的模型。
即使你不拥有这个代码,你可以创建另一个DLL,它将原始的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.
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();
};
Foo* Foo_Create() { return new Foo(); }
int Foo_Bar(Foo* pFoo) { return pFoo->Bar(); }
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.
这篇关于使用c#代码中的c ++ dll中定义的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!