[英]System.BadImageFormatException (HResult=-2147024885) when using Platform Invoke
Given a C library, foo.lib, and a C# console application, bar.exe, I'm trying to perform Platform Invoke. 给定一个C库foo.lib和一个C#控制台应用程序bar.exe,我正在尝试执行Platform Invoke。 However I keep getting the following exception when invoking methods from the library
但是,从库中调用方法时,我始终收到以下异常
System.BadImageFormatException occurred HResult=-2147024885 Message=An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
I have configured the compiler to build bar.exe as x64 and foo.lib is a x64 library. 我已经配置了编译器以将bar.exe构建为x64,而foo.lib是一个x64库。 I've run the following commands to confirm this
我运行以下命令来确认这一点
>corflags bar.exe Microsoft (R) .NET Framework CorFlags Conversion Tool. Version 4.0.30319.1 Copyright (c) Microsoft Corporation. All rights reserved. Version : v4.0.30319 CLR Header: 2.5 PE : PE32+ CorFlags : 1 ILONLY : 1 32BIT : 0 Signed : 0 >dumpbin /headers foo.lib ... File Type: LIBRARY FILE HEADER VALUES 8664 machine (x64) 3 number of sections 53B535D4 time date stamp Thu Jul 03 12:52:04 2014 10E file pointer to symbol table 8 number of symbols 0 size of optional header 0 characteristics ...
I'm certain that foo.lib is the library being loaded, as I tried deleting it, which results in a System.DllNotFoundException. 我确定foo.lib是正在加载的库,因为我尝试将其删除,这导致System.DllNotFoundException。
Any ideas of what might be wrong would be much appreciated. 任何关于什么地方可能出问题的想法将不胜感激。
Edit The exception occurs when I attempt to invoke the library the first time. 编辑第一次尝试调用库时,发生异常。 I have a static class with the following declarations
我有一个带有以下声明的静态类
private static class NativeMethods
{
private const string libname = "foo.lib";
[DllImport(NativeMethods.libname)]
public static extern void foo_method();
}
And the exception occurs in the first call to 并且第一次调用时会发生异常
NativeMethods.foo_method()
An attempt was made to load a program with an incorrect format
试图加载格式错误的程序
That exception message is very accurate. 该异常消息非常准确。 A .lib file is indeed not the correct format.
.lib文件确实不是正确的格式。 Only a linker knows how to use them when it creates a file with the correct format.
只有链接程序知道使用正确格式创建文件时如何使用它们。 A DLL.
DLL。
You'll need to create another project in your solution to create the DLL. 您需要在解决方案中创建另一个项目来创建DLL。 The foo_method() needs to be exported from that DLL.
需要从该DLL中导出foo_method()。 That tends to be a bit tricky when you start with a .lib, you'll have to use a .def file to name the exports.
以.lib开头时,这往往有些棘手,您必须使用.def文件来命名导出。 Much easier to do with
__declspec(dllexport)
. 使用
__declspec(dllexport)
容易__declspec(dllexport)
。 Unclear how you got that .lib but if you built it yourself then you should definitely consider altering the project so it creates the proper executable file. 不清楚如何获取该.lib,但是如果您自己构建它,那么您绝对应该考虑更改项目,以便它创建适当的可执行文件。 A DLL.
DLL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.