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

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

问题描述

我有一个用 c++ 编写的 dll,我需要在我的 c# 代码中使用这个 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 不是我的代码.

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

推荐答案

没有办法在 C# 代码中直接使用 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();
};
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; }

现在是将这些方法 PInvoking 到您的 C# 代码中的问题

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

缺点是你将有一个笨拙的 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.

即使您不拥有此代码,您也可以创建另一个 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++ dll 中定义的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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