Error when trying to load dll – An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

32bit-64bitdllimportvisual c++visual studio 2010winapi

Iam using a 3rd party c++ dll in my asp.net web application.

dll - 64-bit
asp.net Platform - Any Cpu
asp.net Framework - 4.0 (vs 2010)
System Os - Win 7 Professional (64-bit)

I have placed the dll in the Applications folder and called the dll with its full path as:

[DllImport(@"D:\Application\Sampledll.dll",
            EntryPoint = "SampleFunc",
            CharSet = CharSet.Ansi,
            CallingConvention = CallingConvention.StdCall)]
    public static extern int SampleFunc(char[] ch1, char[] ch2);

But I got the below result:

An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

When searched with the Error code: 0x8007000B – It meant 'Using 32-bit dll on 64-bit system'

But the dll is 64-bit dll….

Any how I tried the solution of this error by changing the Target Platform of VS to 'x86' & 'x64' and setting 'Enable 32-Bit Application' property of IIS to 'True'

But got the same error………

Can any one help to get around this problem….

Best Answer

Error code 0x8007000B is the COM error code that represents the Win32 error ERROR_BAD_FORMAT. Normally when a 32 bit process tries to load a 64 bit DLL, or vice versa, the error code is ERROR_BAD_EXE_FORMAT which would appear as 0x800700C1 when wrapped in a COM error code.

Therefore, I think that the problem is not a 32/64 bit mismatch. The most likely explanation is that the DLL, or one of its dependencies, is corrupt.

In order to debug this I would remove the complexity of IIS. You've got added layers of p/invoke and IIS to deal with. First of all make sure that you can load this DLL from another native program. Create a 64 bit C++ console app in VS that does this:

#include <windows.h>
#include <iostream>

int main()
{
    if (!LoadLibraryA("D:\\Application\\Sampledll.dll"))
    {
       std::cout << GetLastError() << std::endl;
    }
}

See what happens when you run that. If you get an error code, what value is it? Is it ERROR_BAD_FORMAT? At this point I'd use Dependency Walker in Profile mode to try to work out which DLL is the trouble maker.