Running c# application with C++ dll generates unable to load exception

0

I'm trying to get a simple C/C++ dll working in a .net (visual studio 2017 with framework 4.x) but all I'm getting is:

System.DllNotFoundException: 'Unable to load DLL 'OurDll.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)'

I am using a sample dll from here (it includes a download to the source and full binary build): https://www.c-sharpcorner.com/uploadfile/tanmayit08/unmanaged-cpp-dll-call-from-managed-c-sharp-application/

But just for ease, the dll is simply this:

#include <stdio.h>
extern "C"  
{
   __declspec(dllexport) int add(int a,int b) 
   {
          return a+b;
   }
   __declspec(dllexport) int subtract(int a,int b) 
   {
          return a-b;
   }
}

It is a 32 bit dll as shown in the project: Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">

The c# code is this:

    [DllImport("OurDll.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern int subtract(int a, int b);
  • The dll is set to export with the program, it is in the folder with the executable.
  • I've explicitly made the program x86 too
  • I've even used their sample bin folder and it doesn't work

So I figure between 2010 and 2018 something has changed :), for example I'm on 64 bit, but I assumed creating an x86 application or running it from their binaries would solve this...

I have also tried putting the full path in, so it is not the path that is at fault and from searching the internet it is not some other externally linked dll.

I have even used corflags to explicitly set everything as 32bit required Any help would be appreciated.

c#
c++
asked on Stack Overflow May 31, 2018 by Neil Walker • edited May 31, 2018 by Neil Walker

1 Answer

0

Solved the problem. The C++ was compiled with /MD with Visual Studio 2015. I only had the runtimes for all versions except 2015. Compiling statically with /MT fixed it.

So the general gist is you need the c++ runtime library installed, or compile your code with the runtime statically to get it to work.

thanks for all your help. Hopefully this may help somebody.

answered on Stack Overflow Jun 6, 2018 by Neil Walker

User contributions licensed under CC BY-SA 3.0