C# based DLL wrapping C based DLL Usage Problem

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!

c#
c
dll
interop
wrapper
asked on Stack Overflow Jul 7, 2020 by Harsh-Sinha • edited Jul 8, 2020 by Harsh-Sinha

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0