Search code examples
.net.net-coredllexportcoreclr

Using dynamic library with native code(build with framework v4.0) in dotnet core


I had build a dll build using dotnet framework v4.0. The code in the library is like below

`extern "C"  
 {
      __declspec(dllexport) int add(int a,int b) 
      {
          printf("Unmanaged add()");
          return a+b;
      }
      __declspec(dllexport) int subtract(int a,int b) 
      {
          printf("Unmanaged subtract()");
          return a-b;
      }
}`

Now i need to refer this dll in .Net Core Application. For that i have made the Nuget package containing this dll and finally installed this nuget package.

The dll is referenced is quite visible in project.json file under its dependency section.

Now the .Net Core Application is like this

{

        [DllImport("vs2010_nativelib.dll", CallingConvention =                                                    CallingConvention.Cdecl)]
        public static extern int subtract(int a, int b);`

        [DllImport("vs2010_nativelib.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int add(int a, int b);

        public static void Main(string[] args)
        {
            Console.WriteLine("Inside Managed Dot Net Core 1.0 Application ");
            Console.WriteLine("Calling Unamanged add : {0}", add(10, 20));
            Console.WriteLine("Calling Unamanged subtract : {0}", subtract(30, 20));
            Console.ReadLine();
        }
}

While running this application, the moment it calls add(10, 20) function of unmanaged dll it throws BadImageFormatException with this message An attempt was made to load a program with an incorrect format.

So where is the problem ? Does .Net Core cannot use these types of libraries or there something else i am missing ?


Solution

  • Make sure that the native code dll and the .Net core application dll are of same platform as your Machine configuration(ex : 64 bit).