Call exported functions from C++ DLL library in C#

0

I have no problems to call C++ DLL functions from C# by using dynamic linking, but got problem when I tried to make it in dynamic way:

Trying to get DLL handler:

var DLL = Assembly.LoadFile(@"C:\project\mydll.dll");

And got exception:

An unhandled exception of type 'System.BadImageFormatException' occurred in mscorlib.dll

Additional information: The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)

How to solve this problem?

c#
c++
dll
asked on Stack Overflow Mar 17, 2017 by vico • edited Mar 17, 2017 by Uwe Keim

2 Answers

1

Assembly.LoadFile is used to load .NET assemblies, it cannot load an a DLL that does not contain an assembly.

You'll need to use PInvoke to access the functions in the DLL. Also, you'll need to make sure that the names of the exported functions are not mangled as it can be almost impossible to work out what the function name is, and the name can change when built with different versions of a C++ compiler.

answered on Stack Overflow Mar 17, 2017 by Sean • edited Mar 17, 2017 by Sean
0

The Assembly.LoadFile should only be used for loading .NET assemblies. Pure Win32 dlls cannot be loaded this way.

In order to load a Win32 library in managed code use LoadLibrary Win32 call via PInvoke.

answered on Stack Overflow Mar 17, 2017 by Dmitry Egorov • edited Mar 17, 2017 by Dmitry Egorov

User contributions licensed under CC BY-SA 3.0