在 C++ 代码中使用 C# dll

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19144006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:14:21  来源:igfitidea点击:

Using C# dll in C++ code

c#c++visual-c++dll

提问by Sunrise

I need to integrate this C# dllin my C++ code. I want to call some functions written in C# from dll and the rest of code write in C++. What is the easiest and quickest way to do it? The program will be executed only on Windows.

我需要 在我的 C++ 代码中集成这个C# dll。我想从 dll 调用一些用 C# 编写的函数,其余的代码用 C++ 编写。最简单快捷的方法是什么?该程序将仅在 Windows 上执行。

采纳答案by Simon Mourier

There are basically two cases to call a .NET DLL from unmanaged code:

从非托管代码调用 .NET DLL 基本上有两种情况:

  1. The .NET DLL exposes a COM interface. In this case, you can use COM from your C++ code.
  2. The .NET DLL does not expose a COM interface. In this case, you have two possibilities (to make it simple):

    2.a. host the CLR as described here: Loading the Common Language Runtime into a Process
    2.b. write a piece of managed C++ code (another DLL - written in C++/CLI) to wrap the .NET DLL and expose 'old way' DLL exports to unmanaged clients.

  1. .NET DLL 公开了一个 COM 接口。在这种情况下,您可以在 C++ 代码中使用 COM。
  2. .NET DLL 不公开 COM 接口。在这种情况下,您有两种可能性(为了简单起见):

    2.a. 按照此处所述托管 CLR:将公共语言运行时加载到进程
    2.b 中。编写一段托管 C++ 代码(另一个 DLL - 用 C++/CLI 编写)来包装 .NET DLL 并将“旧方式”DLL 导出公开给非托管客户端。

I don't specifically know the sharpbox system, but it looks like it's pure .NET and does not expose COM interfaces, so 2.b might be the best way to do it (not so easy...). Maybe it has a REST/Web easier API you could use.

我不是特别了解sharpbox系统,但它看起来像纯.NET并且不公开COM接口,所以2.b可能是最好的方法(不是那么容易......)。也许它有一个你可以使用的 REST/Web 更简单的 API。

PS: you can also add exports to a .NET DLL. This is described here: Is is possible to export functions from a C# DLL like in VS C++?but it's kinda hacky.

PS:您还可以将导出添加到 .NET DLL。这在这里描述:Is is possible to export functions from a C# DLL like in VS C++? 但它有点hacky。