1
votes

Given a C library, foo.lib, and a C# console application, bar.exe, I'm trying to perform 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. 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.

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()
1
Where do you get that exception? Can you post some code?Lasse V. Karlsen
@LasseV.Karlsen Please see edit - this is very simplified, but hopefully the meaning is clear.Mads Ravn
And you're sure your program is running as 64-bit? And have you verified that any dll's your dll is referencing is also 64-bit?Lasse V. Karlsen
And @HansPassant is right though he removed his comment, I missed that detail. Never mind my comments. The exception is correct, you're loading something that isn't a dll. You can only use a .lib file with a linker, it's not a dll, and DllImport requires a dll.Lasse V. Karlsen

1 Answers

0
votes

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. Only a linker knows how to use them when it creates a file with the correct format. A DLL.

You'll need to create another project in your solution to create the DLL. The foo_method() needs to be exported from that DLL. 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. Much easier to do with __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. A DLL.