从Unmanged Code VC ++调用用C#编写的托管DLL

问题描述:

我有一个用C#编写的dll,我想在我的非托管VC ++应用程序中使用它.我发现的每一种方式都是令人费解的,并且要求我更改DLL代码本身.如果我无权访问DLL源代码该怎么办.任何帮助将不胜感激.

I have a dll that is written in C# and I would like to use it in my Unmanaged VC++ application. Every way I find is convoluted and requires that I change the DLL code itself. What if I do not have access to the DLL source code. Any help would be appreciated.

您应该将C ++代码编译为托管(混合模式),或者将托管(混合模式)C ++ DLL添加到您的C ++ DLL中.专案.

您选择哪一个将主要取决于您现有的代码.如果您的应用程序很复杂,则可能很难对其进行转换,以使其可以编译并与/clr一起使用.在这种情况下,添加额外的DLL可能是避免在其他情况下可能发生冲突的更简单解决方案.

但是,如果您的应用程序可以轻松地编译并可以与/clr一起正常使用,则可以避免使用这种方式进行额外的间接访问.
You should either compile your C++ code as managed (mixed-mode) or add a managed (mixed-mode) C++ DLL to your project.

Which one you choose will depend mainly on your existing code. If you application is quite complex, then it might be difficult to convert it so that it would compile and works with /clr. In that case, adding an extra DLL might be the simpler solution to avoid conflicts that might otherwise arise.

But if you application can easily be compiled and properly works with /clr, you would avoid an extra indirection doing that way.


有一种方法可以将.NET程序集中的方法导出为非托管方法. ,因此无论是否为C ++,非托管代码都可以将其用作常规非托管DLL.这种方法不是众所周知的,但是严格地基于CLR标准.问题是高级CLR语言无法实现,但IL可以实现.

为高级CLR(.NET)语言提供此功能的技巧.想法是引入一种特殊的属性,使之成为导出到不受管"的方法.构建工具应将程序集从其二进制形式反汇编为IL,使用属性修改IL代码以添加导出,然后将其从修改后的IL再次组装为可执行程序集.生成的程序集可以用作常规的非托管DLL.该构建步骤是完全自动化的.而且所使用的不需要熟悉IL.

您可以在以下CodeProject文章中找到解决方案:
非托管代码可以包装托管方法 [如何自动将.NET功能导出到非托管程序 [
There is a method of exporting methods from a .NET assembly as unmanaged, so it can be used as a regular unmanaged DLL by the unmanaged codes, C++ or not. This method is not well-known, but it is strictly based on the CLR standard. The problem is that is is not possible to achieve with high-level CLR languages but with IL it can be done.

The trick it to provide this functionality to high-level CLR (.NET) languages. The idea is to introduce a special attribute use to make a method as "export to unmanaged". A build tool should disassemble the assembly from its binary form to IL, modify IL code using the attribute to add the export and assemble it from modified IL to executable assembly again. A resulting assembly can be used as a regular unmanaged DLL. This build step is fully automated; and the used does not need to be familiar with IL.

You can find the solution in the following CodeProject articles:
Unmanaged code can wrap managed methods[^],
How to Automate Exporting .NET Function to Unmanaged Programs[^].

—SA