I’m trying to import some functions from 32 bit and 64 bit DLLs written in unmanaged C++ into my C# project. As a sample, I did this:
C++ DLL function
long mult(int a, int b) {
return ((long) a)*((long) b);
}
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
class DynamicDLLImport
{
private IntPtr ptrToDll;
private IntPtr ptrToFunctionToCall;
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int Multiply(int a, int b);
private Multiply multiply;
public DynamicDLLImport(string dllName)
{
ptrToDll = LoadLibrary(dllName);
// TODO: Error handling.
ptrToFunctionToCall = GetProcAddress(ptrToDll, "mult");
// TODO: Error handling.
// HERE ARGUMENTNULLEXCEPTION
multiply = (Multiply)Marshal.GetDelegateForFunctionPointer(ptrToFunctionToCall, typeof(Multiply));
}
public int mult_func(int a, int b)
{
return multiply(a, b);
}
~DynamicDLLImport()
{
FreeLibrary(ptrToDll);
}
}
class DLLWrapper
{
private const string Sixtyfour = "c:\\Users\\Hattenn\\Documents\\Visual Studio 2010\\Projects\\ConsoleApplication2\\ConsoleApplication2\\easyDLL0_64.dll";
private const string Thirtytwo = "c:\\Users\\Hattenn\\Documents\\Visual Studio 2010\\Projects\\ConsoleApplication2\\ConsoleApplication2\\easyDLL0.dll";
// [DllImport(Sixtyfour)]
// public static extern int mult(int a, int b);
[DllImport(Thirtytwo)]
public static extern int mult(int a, int b);
}
class Program
{
static void Main(string[] args)
{
int a = 5;
int b = 4;
DynamicDLLImport dllimp = new DynamicDLLImport("easyDLL0.dll");
Console.WriteLine(DLLWrapper.mult(a, b));
//Console.WriteLine(dllimp.mult_func(a, b));
Console.ReadKey();
}
}
}
I can’t seem to get it to work. Here are the error messages that I get:
- When I use the DLLWrapper class with the 32 bit DLL file I get “DLLNotFoundException”, but the DLL file is exactly in that path.
- When I use the DLLWrapper class with the 64 bit DLL file and change the “Platform Target” property to “x64” I get the same “DLLNotFoundException”, if I try to build with “x86” then I get “BadImageException”.
- When I use the DynamicDLLImport class, I always get “ArgumentNullException” at the line commented with “HERE ARGUMENTNULLEXCEPTION” in the code.
What am I doing wrong?
The problem turned out to be that the dll was deployed in debug mode and not in a correct way. When it was deployed in release mode, everything seemed to work fine. Anyone having a similar problem should know that compiling the dll in debug mode and just copying it to another computer is not the right way to do it.