Click here to Skip to main content
15,890,512 members
Articles / Programming Languages / C#
Article

Dynamic Invoke from Unmanaged DLL

Rate me:
Please Sign up or sign in to vote.
3.44/5 (9 votes)
4 Jan 2005 91.6K   31   21
This article explains invoking unmanaged DLL functions from C#.

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:

C#
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.

C#
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;
  }

Sample calling of the method is as below:

C#
DynamicDllFunctionInvoke(@"c:\getmyversion.dll","GetDllVersion");

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect
Turkey Turkey
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
merikin28-Jun-10 4:14
merikin28-Jun-10 4:14 
Questionreal dynamic invoke Pin
fredarmoni21-Aug-07 0:10
fredarmoni21-Aug-07 0:10 
AnswerRe: real dynamic inoke Pin
Shawn-USA5-Aug-13 15:21
Shawn-USA5-Aug-13 15:21 
QuestionHow to Unload a DLL Pin
Ronakkumar Patel31-May-07 13:21
Ronakkumar Patel31-May-07 13:21 
AnswerRe: How to Unload a DLL Pin
Shawn-USA5-Aug-13 15:24
Shawn-USA5-Aug-13 15:24 
Questionwhen load dll of vc++6.0 its generated error?? Pin
keyur_patel26-Mar-07 21:57
keyur_patel26-Mar-07 21:57 
AnswerRe: when load dll of vc++6.0 its generated error?? Pin
calaquendi26-Mar-07 22:34
calaquendi26-Mar-07 22:34 
QuestionReturned value does not work Pin
Michal Czardybon31-May-06 0:10
Michal Czardybon31-May-06 0:10 
Generalref string Pin
John Orosz17-Mar-05 6:34
John Orosz17-Mar-05 6:34 
QuestionRe: ref string Pin
npat19-Jan-07 11:11
npat19-Jan-07 11:11 
AnswerRe: ref string Pin
Jorge Branco29-Aug-08 10:28
Jorge Branco29-Aug-08 10:28 
GeneralRe: ref string Pin
Jorge Branco29-Aug-08 10:39
Jorge Branco29-Aug-08 10:39 
QuestionDllImport Attribute? Pin
Marc Clifton4-Jan-05 5:25
mvaMarc Clifton4-Jan-05 5:25 
AnswerRe: DllImport Attribute? Pin
Chris Richardson4-Jan-05 10:40
Chris Richardson4-Jan-05 10:40 
GeneralRe: DllImport Attribute? Pin
Marc Clifton4-Jan-05 10:56
mvaMarc Clifton4-Jan-05 10:56 
GeneralRe: DllImport Attribute? Pin
Chris Richardson4-Jan-05 11:06
Chris Richardson4-Jan-05 11:06 
AnswerRe: DllImport Attribute? Pin
calaquendi4-Jan-05 20:09
calaquendi4-Jan-05 20:09 
AnswerRe: DllImport Attribute? Pin
Leonardo Pessoa5-Jan-05 0:20
Leonardo Pessoa5-Jan-05 0:20 
GeneralRe: DllImport Attribute? Pin
Superfan25-Jan-05 15:01
Superfan25-Jan-05 15:01 
GeneralRe: DllImport Attribute? Pin
Leonardo Pessoa25-Jan-05 23:23
Leonardo Pessoa25-Jan-05 23:23 
I hope you understand that passing the wrong set of parameters to a method can cause unpredictable results, from wrong operation to total failure of your system. Also, how will you change the set or arguments passed to the function during runtime?

I'm afraid there is no way, managed or unmanaged, to retrieve the list of parameters to an unmanaged function. Believe me, I spent a lot looking for it too. You will have to go through the PE header by yourself. This is the reason why I gave up using Reflection Emit; consumes too many resources and time for no benefits (at least for this purpose).


[]'s
Harkos
---
"Money isn't our god, integrity will free our soul."
Cut Throat - Sepultura
GeneralRe: DllImport Attribute? Pin
Superfan26-Jan-05 5:34
Superfan26-Jan-05 5:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.