在 C# 应用程序中使用 C++ 类 DLL [英] Using C++ Class DLL in C# Application

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

问题描述

我有一个非托管 C++ DLL,它仅导出一个类(不是 COM...它只是一个简单的 C++ 类)作为其接口.我想在 C# 中使用这个类,但被告知它不能仅仅导入到 C# 中.

I have an unmanaged C++ DLL which merely exports a single class (not COM...it's just a simple C++ class) as its interface. I want to use this class in C# but am told that it cannot merely be imported into C#.

在我的 C# 应用程序中使用这个类的正确方法是什么?

What is the right way to use this class in my C# application?

推荐答案

假设 class Foo 的简单方法:

Simple way assuming class Foo:

  1. 创建一个 C++/CLI 项目,将其命名为 FooWrapper.
  2. 使 FooWrapper 依赖于非托管 dll(但您通常会这样做).
  3. 创建一个托管类 ManagedFoo,其中包含一个 Foo* 类型的私有实例字段.
  4. 在 ManagedFoo 中提供公共包装函数,这些函数转发到底层实例字段.
  5. 可选(虽然推荐):
    • 将参数从 .net 习语(字符串等)转换为 C++ 习语(std::string 或 char*)
    • 捕获非托管异常并抛出托管异常

然后你让你的 c# 代码依赖于 FooWrapper 项目/dll 并确保非托管 dll 正确部署,如何完成取决于非托管 dll 但在同一目录中通常就足够了.

Then you make your c# code depend on the FooWrapper project/dll and ensure that the unmanaged dll is properly deployed with it, how that is done depends on the unmanaged dll but in the same directory is normally sufficient.

如果函数不依赖于类的实例,那么更简单的是 P/Invoke

If the functions do not rely on instances of the class then even simpler is P/Invoke

这篇关于在 C# 应用程序中使用 C++ 类 DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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