I created a C++ DLL and a C# project. (The C# project calls the C++ DLL functions).
The DLL has the following header and cpp file:
// 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(...){
...
}
The c# project calls the function: (and throwing 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(...);
.
.
.
and ... no matter what I try, I always get the same error: "System.BadImageFormatException: 'An attempt was made to load a program with an incorrect format. (0x8007000B)'"
I have read and implement all the possible solutions to this problem (64-bits calling 32-bits and vice versa) including changing the 'Platform target' to 'Any CPU' for both projects. I tried to add a reference to the DLL, but it is'nt possible (even, that apparently this is not possible for all DLL anyway).
*The DLL created step by step by the tutorial https://docs.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=msvc-160.
*Using Visual Studio 2019.
Function implementation must be with extern "C"
extern "C"
{
HEADER_API bool function(...){
...
}
}
User contributions licensed under CC BY-SA 3.0