简体   繁体   English

在C#中使用C ++ dll对象

[英]Using C++ dll object within C#

I have a third party C++ .dll which exports some classes which I wish to use from C#. 我有一个第三方C ++ .dll,它导出了一些我希望从C#使用的类。 The dll is a Win32 application and I'm working on Windows 8.1 using VS2013. 该dll是Win32应用程序,我正在使用VS2013在Windows 8.1上工作。 When I set up the C# program running under 'Any CPU', I get the error "System.BadImageFormatException". 设置在“任何CPU”下运行的C#程序时,出现错误“ System.BadImageFormatException”。 I've read other places that this can be caused by combining x86 and x64. 我已经读过其他地方,这可能是由于x86和x64组合引起的。 So I recompiled the C# program as x86. 因此,我将C#程序重新编译为x86。 Now I get "Unable to load DLL 'libsword.dll': The specified module could not be found". 现在,我得到“无法加载DLL'libsword.dll':找不到指定的模块”。 I've made sure the dll is in the proper directory. 我确保dll在正确的目录中。

All of this works just fine on Linux using Mono. 所有这些在使用Mono的Linux上都能正常工作。

At this point, I've got no idea how to proceed. 在这一点上,我不知道如何进行。

Thanks, Jon 谢谢,乔恩

BadImageFormatException is thrown when you treat regular native C++ code in a DLL as if it was .NET code. 当您将DLL中的常规本机C ++代码视为.NET代码时,将引发BadImageFormatException。 .NET also puts code in the .DLL files. .NET还将代码存储在.DLL文件中。

You'll need to create C# declarations for the C++ code, so that .NET knows how to transition from managed (.NET/C#) code to native (C++) code. 您需要为C ++代码创建C#声明,以便.NET知道如何从托管(.NET / C#)代码过渡到本机(C ++)代码。 This is fairly complicated, depending on what the code in your 3rd party library looks like. 这非常复杂,具体取决于第3方库中的代码是什么样的。 Too much for me to speculate what you need to do. 对我来说,太多想你需要做什么。

The problem was in the C++ library, which was originally written and developed for Linux. 问题出在C ++库中,该库最初是为Linux编写和开发的。 Export was defined as: 导出定义为:

define SWDLLEXPORT _declspec( dllexport )

Which was used as: 用作:

const char * SWDLLEXPORT  function_name(args)

which worked in Linux but not in Windows. 在Linux中有效,但在Windows中无效。 Changing the function signature to: 将功能签名更改为:

const char SWDLLEXPORT * function_name(args)

Works in both Linux and Windows. 在Linux和Windows中均可使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM