使用在C中定义的类++在C#code DLL [英] using a class defined in a c++ dll in c# code

查看:138
本文介绍了使用在C中定义的类++在C#code DLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个是用C ++编写一个DLL,我需要在我的C#code使用此DLL。搜索后我发现,使用P / Invoke会给我获得我所需要的功能,但是这些功能在一个类中定义,并使用非静态私有成员变量。所以,我需要能够创建这个类的一个实例正确使用的功能。我如何才能获得这个类,这样我可以创建一个实例?我一直无法找到一个方法来做到这一点。

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.

我想我应该注意的是,C ++ DLL是不是我的code。

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

推荐答案

有没有办法直接使用C#code C ++类。您可以使用的PInvoke以间接的方式来访问你的类型。

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.

其基本模式是在类Foo每个成员函数,创建一个调用到成员函数相关的非成员函数。

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; }

现在是PInvoking这些方法到C#code

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")]
pulbic static extern void Foo_Delete(IntPtr value);

缺点是您将有一个尴尬的IntPtr通过左右,但它是一个有点简单的事情创建一个围绕这个指针是C#包装类创建一个更实用的模式。

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.

即使你并不拥有这个code,您可以创建另一个DLL它包装原来的DLL,并提供一个小型的PInvoke层。

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#code DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆