尝试将C++dll导入C#时出现奇怪的System.BadImageFormatException
Bizarre System.BadImageFormatException when trying to import C++ dll into C#
这是相关的C#位
KrautVK.cs
internal static class KrautVK{
[DllImport("lib\krautvk", CallingConvention = CallingConvention.Cdecl, EntryPoint = "init")]
internal static extern int Init(int width, int height, string title, bool fullscreen);
[DllImport("lib\krautvk", CallingConvention = CallingConvention.Cdecl, EntryPoint = "windowShouldClose")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool WindowShouldClose();
[DllImport("lib\krautvk", CallingConvention = CallingConvention.Cdecl, EntryPoint = "pollEvents")]
internal static extern void PollEvents();
[DllImport("lib\krautvk", CallingConvention = CallingConvention.Cdecl, EntryPoint = "terminate")]
internal static extern void Terminate();
}
这是(相关的)C++代码:
KrautVK.h
#ifndef KRAUTVK_H_
#define KRAUTVK_H_
#include <cstdio>
#include <vector>
#include <iostream>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#define EXPORT extern "C" __declspec(dllexport)
EXPORT int init(int w, int h, char *title, int f);
EXPORT int windowShouldClose();
EXPORT void pollEvents();
EXPORT void terminate();
我非常清楚,如果构建格式不匹配(即从64位应用程序调用32位dll),DllImport可能会抛出System.BadImageFormatException
。然而,事实并非如此。两者都是针对同一CPU构建的。
经过一些故障排除,我发现它完全是由iostream
和vector
包含引起的。通过删除这些include,错误就会消失,调用也会正常工作。事实上,在我开始实现需要这些include的代码之前,我并没有遇到任何问题。然而,我需要这些内容,而一天的大部分研究都没有发现这种奇怪行为的文件或解释,事实上,许多例子都使用了iostream
。
如果可以的话,我同时使用Jetbrains Rider和Clion。
使用Dependency Walker,我缺少3个dll:
- libstdc++-6.dll
- libgcc_s_seh-1.dll
- 和libwinpthread-1.dll
如果使用MingW环境,它们是必需的运行库。把它们放到可执行文件文件夹中就成功了。它们可以在{Your MingW/MingW64 installation folder}bin
中找到
相关文章:
- 没有找到相关文章