Monday, December 1, 2014

Call unmanaged dll dynamically

Hello,


Maybe this article http://ift.tt/1ytvTlh is what you explained in your first example.


And to achieve what you need, you can refer to the following article:


http://ift.tt/1waKL9O



public object DynamicDllFunctionInvoke( string DllPath, string EntryPoint )
{
// Version string definition
byte[] verstr = new byte[1024];
//Define return type of your dll function.
Type returnType = typeof(int);
//out or in parameters of your function.
Type [] parameterTypes = {typeof(byte[])};
object[] parameterValues = {verstr};
string entryPoint = entrypoint;

// Create a dynamic assembly and a dynamic module
AssemblyName asmName = new AssemblyName();
asmName.Name = "tempDll";
AssemblyBuilder dynamicAsm =
AppDomain.CurrentDomain.DefineDynamicAssembly(asmName,
AssemblyBuilderAccess.Run);
ModuleBuilder dynamicMod =
dynamicAsm.DefineDynamicModule("tempModule");

// Dynamically construct a global PInvoke signature
// using the input information
MethodBuilder dynamicMethod = dynamicMod.DefinePInvokeMethod(
entryPoint, DllPath, MethodAttributes.Static | MethodAttributes.Public
| MethodAttributes.PinvokeImpl , CallingConventions.Standard,
returnType, parameterTypes, CallingConvention.Winapi,
CharSet.Ansi);

// This global method is now complete
dynamicMod.CreateGlobalFunctions();

// Get a MethodInfo for the PInvoke method
MethodInfo mi = dynamicMod.GetMethod(EntryPoint);
// Invoke the static method and return whatever it returns
object retval = mi.Invoke(null, parameterValues);
// Filled verstr paramter.
MessageBox.Show(System.Text.ASCIIEncoding.ASCII.GetString(verstr));
return retval;
}

You may also want to know reflection by refer to the following article:


http://ift.tt/1kyQG30


Regards,







Barry

We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.

Click HERE to participate the survey.


No comments:

Post a Comment