我正在尝试使用调用非托管 C++ .dll 的 WPF 使用 C# 创建一个 UI。我试过使用 Platform Invoke 方法,也尝试过使用/clr 选项编译 C++ 代码,这样更好。这两种方法都可以正常工作,直到 C++ .dll 使用任何包含标准 Lua 头文件的代码。可以肯定的是,C++ 代码在编译为 .exe 时以及在另一个 C++ 项目调用 .dll 时都能正常工作。
只是为了测试,C# 端类似于下面使用 PInvoke 时的第一个代码块:
namespace ThermoSIM_UI
{
public class CppInterface
{
[DllImport("ThermoSIMDLL_1.2.dll")]
public static extern int TestPassString();
public CppInterface()
{
TestPassString();
}
}
}
C++ .dll 有一个像这样的头文件:
#ifdef THERMOSIMDLL_EXPORTS
#define THERMOSIMDLL_API __declspec(dllexport)
#else
#define THERMOSIMDLL_API __declspec(dllimport)
#endif
extern "C"
{
THERMOSIMDLL_API int TestPassString();
}
正如我所说,这一直有效,直到我在 C++ .dll 中有一个使用 Lua include 的文件:
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "luajit.h"
}
啊,C# 错误是这样的:
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
Additional information: The invocation of the constructor on type 'ThermoSIM_UI.MainWindow' that matches the specified binding constraints threw an exception.
此外,在“输出”窗口中还有:
A first chance exception of type 'System.BadImageFormatException' occurred in ThermoSIM_UI.exe
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
A first chance exception of type 'System.Xaml.XamlObjectWriterException' occurred in System.Xaml.dll
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
Additional information: The invocation of the constructor on type 'ThermoSIM_UI.MainWindow' that matches the specified binding constraints threw an exception.
The program '[8048] ThermoSIM_UI.vshost.exe: Managed (v4.0.30319)' has exited with code -1 (0xffffffff).
BadImageFormatException 似乎与具有不同构建配置的 .dll 之类的事情有关,例如混合 x64 与 x86 之类的东西。反正我还没弄明白。 http://msdn.microsoft.com/en-us/library/system.badimageformatexception(v=vs.110).aspx
有没有人遇到过这个,或者知道为什么这个 .dll 变得与 C# 不兼容?
最佳答案
遵循@Schollii 的建议成功了:如果我自己用 Visual Studio 构建 Lua,它就可以工作。这篇 SO 帖子有所帮助,稍作修改:Lua in visual studio 2012? .
- 下载 Lua 文件 lua.org/download.html
- 创建了一个新的 Visual Studio 项目来创建一个库。我做了一个静态库。
- 删除解释器文件 lua.c,因为它与 luac.c 冲突
- 使用与我的 c++ dll 相同的设置进行编译,即 x64,Release。
现在 C# 项目可以调用 C++ dll。
关于c# - 在 C++ DLL 中包含 Lua 使其与 C# 不兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22306967/