我创建了一个C++DLL和一个C#项目。(C#项目调用C++DLL函数)。
DLL具有以下头和cpp文件:
// Header.h
#ifdef HEADER_EXPORTS
#define HEADER_API __declspec(dllexport)
#else
#define HEADER_API __declspec(dllimport)
#endif
#pragma once
#include <stdio.h>
#include <stdlib.h>
extern "C" HEADER_API bool function(...);
// cpp file - only function, no class!
bool function(...){
...
}
C#项目调用函数:(并抛出BadImageFormatException)
using System;
using System.Runtime.InteropServices;
namespace tempProject
{
public partial class ViewResultWin : Form
{
[DllImport(DLL_PATH)]
public static extern bool function(...);
.
.
.
public ViewResultWin()
{
// An error occurs here
bool answer = function(...);
.
.
.
而且……无论我尝试什么,我总是得到相同的错误:“System.BadImageFormatException:试图加载格式不正确的程序。(0x8007000B)'”
我已经阅读并实现了这个问题的所有可能的解决方案(64位调用32位,反之亦然),包括将两个项目的“平台目标”更改为“任何CPU"。我试图添加一个对DLL的引用,但这是不可能的(甚至,显然这不可能对所有DLL都是如此)。
*教程https://docs.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=msvc-160逐步创建的DLL。
*使用Visual Studio 2019。
函数实现必须使用
extern "C"
{
HEADER_API bool function(...){
...
}
}