Introduction
This article demonstrates how to call an unmanaged MFC DLL function from a C# code. Code uses Reflection
namespace. To use code snippets below, you must add the following:
using System.Reflection.Emit;
using System.Reflection;
Imagine you have an MFC DLL (getmyversion.dll) with function named int GetDllversion(char* verstr)
which returns your DLL's version in verstr
.
The below function creates a dynamic assembly object. And DefinePInvokeMethod
method creates a method which we will use to access our DLL function. To complete our global ops for our dynamic module, call CreateGlobalFunctions
. Using GetMethod
function of our previously created method, we can invoke our MFC DLL function.
public object DynamicDllFunctionInvoke( string DllPath, string EntryPoint )
{
byte[] verstr = new byte[1024];
Type returnType = typeof(int);
Type [] parameterTypes = {typeof(byte[])};
object[] parameterValues = {verstr};
string entryPoint = entrypoint;
AssemblyName asmName = new AssemblyName();
asmName.Name = "tempDll";
AssemblyBuilder dynamicAsm =
AppDomain.CurrentDomain.DefineDynamicAssembly(asmName,
AssemblyBuilderAccess.Run);
ModuleBuilder dynamicMod =
dynamicAsm.DefineDynamicModule("tempModule");
MethodBuilder dynamicMethod = dynamicMod.DefinePInvokeMethod(
entryPoint, DllPath, MethodAttributes.Static | MethodAttributes.Public
| MethodAttributes.PinvokeImpl , CallingConventions.Standard,
returnType, parameterTypes, CallingConvention.Winapi,
CharSet.Ansi);
dynamicMod.CreateGlobalFunctions();
MethodInfo mi = dynamicMod.GetMethod(EntryPoint);
object retval = mi.Invoke(null, parameterValues);
MessageBox.Show(System.Text.ASCIIEncoding.ASCII.GetString(verstr));
return retval;
}
Sample calling of the method is as below:
DynamicDllFunctionInvoke(@"c:\getmyversion.dll","GetDllVersion");