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

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

问题描述

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



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

解决方案

简单的方式假设Foo:


  1. 创建一个C ++ / CLI项目,调用这个FooWrapper。

  2. 使FooWrapper依赖于非托管dll(不过你通常会这样做)。

  3. 创建一个托管类ManagedFoo,其中包含一个类型为Foo *的单个私有实例字段。

  4. 在ManagedFoo中提供了转发到底层实例字段的公共包装函数。
  5. 可选(虽然推荐):


    • 将参数从.net idioms(字符串等)转换为C ++成语(std :: string或char *)

    • 捕获非托管异常并抛出管理的异常




    1. 然后,您使您的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:

      1. Create a C++/CLI project, call this FooWrapper.
      2. Make FooWrapper depend on the unmanaged dll (however you normally would).
      3. Create a managed class ManagedFoo which contains a single private instance field of type Foo*.
      4. provide public wrapping functions in ManagedFoo which forward on to the underlying instance field.
      5. 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

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

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