1

I have code written in ANSI C that I would like to use in C#. I have compiled the C code into a DLL and created C# wrapper classes to interop with the C code. The point of the wrapper is to simplify a users interaction with the underlying C code.

[DllImport(DLL, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void PrintHelloWorld();

public void PrintHelloWorldC()
{
    PrintHelloWorld();
}

Above is a simplified example of what I have done so far. Now, I am trying to create a DLL from the C# wrapper classes I wrote. From here I could give both the DLLs created and someone would be able to interact with the C# based DLL to interact with the underlying C based DLL. Below is what I have done and what problem I am having.

  1. I compile the C code into a DLL in Visual Studio 2019 with my Configuration=Release and Platform=Win32.
  2. I compile my C# classes into a DLL in Visual Studio 2019 with my Configuration=Release, Platform=Win32, and Platform Target as x86.
  3. I create a new project and link my C# DLL and set Platform Target as x86.
  4. I put my C DLL into the Debug folder of the project so that it is available to the C# DLL through the marshal directive.

I try to make a call into the C# DLL and below are the chain of events occurring.

  1. Program calls C# DLL method PrintHelloWorldC() and is successful
  2. Within PrintHelloWorldC() it tries to make a call to PrintHelloWorld();.

Following Error Occurs:

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

My research yielded that it was most likely a mismatch in Platform Target between the DLLs and Test Project, however, I have double checked all the configurations and they should all be compiled for x86.

Below is what additional testing I have done.

  1. Created a C# Project, and wrote simple code to make a call directly into the C based DLL. This works fine.

It seems that as soon as I try to use the two DLLs on top of each other in another project I start facing issues.

Any help or guidance is appreciated. Thanks in advance!

  • Are you trying to run this code as a unit test inside Visual Studio? – BlueStrat Jul 07 '20 at 23:22
  • I think the error is due to a align issue. Are you using AnyCPU? AnyCPU default to 32 bits and gives error on 64 bits. See following : https://stackoverflow.com/questions/16539413/using-32-bit-dll-on-64-bit-system-shows-0x8007000b-error – jdweng Jul 07 '20 at 23:29
  • 1
    It will be a 32/64 bit mismatch – David Heffernan Jul 08 '20 at 06:19
  • @BlueStrat Currently I am not running unit tests.@jdweng I am not using AnyCPU, but would be fine with it defaulting to 32 bits for now. – Harsh-Sinha Jul 08 '20 at 17:54

0 Answers0