问题描述
我有一个非托管C ++ DLL,它只是导出一个类(不是COM ...它只是一个简单的C ++类)作为其接口。我想在C#中使用这个类,但是被告知不能仅仅将它导入到C#中。在C#应用程序中使用这个类的正确方法是什么? / p>
简单的方式假设Foo:
- 创建一个C ++ / CLI项目,调用这个FooWrapper。
- 使FooWrapper依赖于非托管dll(不过你通常会这样做)。
- 创建一个托管类ManagedFoo,其中包含一个类型为Foo *的单个私有实例字段。
- 在ManagedFoo中提供了转发到底层实例字段的公共包装函数。
- 可选(虽然推荐):
- 将参数从.net idioms(字符串等)转换为C ++成语(std :: string或char *)
- 捕获非托管异常并抛出管理的异常
- Create a C++/CLI project, call this FooWrapper.
- Make FooWrapper depend on the unmanaged dll (however you normally would).
- Create a managed class ManagedFoo which contains a single private instance field of type Foo*.
- provide public wrapping functions in ManagedFoo which forward on to the underlying instance field.
- Optionally (though recommended):
- convert parameters from .net idioms (strings and the like) to C++ idioms (std::string or char*)
- catch unmanaged exceptions and throw managed ones instead
然后,您使您的c#代码依赖于FooWrapper项目/ dll,并确保非托管ll已正确部署,如何完成取决于非托管DLL,但在相同的目录通常是足够的。
如果函数不依赖类的实例,那么更简单的是P / Invoke
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#.
What is the right way to use this class in my C# application?
Simple way assuming class Foo:
Then you make your c# code depend on the FooWrapper project/dll and ensure that the unmanaged ll is properly deployed with it, how that is done depends on the unmanaged dll but in the same directory is normally sufficient.
If the functions do not rely on instances of the class then even simpler is P/Invoke
这篇关于在C#应用程序中使用C ++类DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!