Click here to Skip to main content
Click here to Skip to main content

Late binding on native DLLs with C#

By , 12 Nov 2001
 

Sample Image - DynInvok.gif

Introduction

Consider the situation where the native, Win32 DLL is unknown at compile time. Perhaps its name or location is stored in the Windows Registry, or is selected by the user from a FileOpen dialog. How can we call a function exported from this library, but only resolved at runtime? The prescribed way to call native functions from the CLR is through PInvoke, using the DllImport attribute, but this must be declared at compile time or, at the very least, generated on the fly using Reflection.Emit. This article will show an alternative way which requires the use of a little x86 assembler to meet our goal.

LoadLibrary

Windows provides two ways to load DLLs into the process of an executable. Either, the DLL can be specified in the imports table and the Windows Loader will map the DLL automatically or the LoadLibrary() Win32 API call can be used. These are called implicit linking and explicit linking respectively. Both these types can be seen in action using Dependency Walker available from http://www.dependencywalker.com/. The CLR, Visual BASIC 6 and the /delayload feature of MSVC6 all use explicit linking to call DLL functions.

We can quite happily call LoadLibrary() from C# to load a DLL into our address space. The problem comes when we try to call a function in the DLL. Win32 provides the GetProcAddress() function to return the memory address of a function exported from the given DLL and we can easily obtain this memory address, but we can do nothing with it. It is simply an integer. The CLR provides no way to jump to this location in memory, passing appropriate parameters too.

The CLR does allow us to do the reverse and pass a pointer to a managed function to a DLL using the delegate keyword, but there is no way to specify that a value returned from an unmanaged API call should be treated as a delegate. Perhaps we may see this in .Net version 2, but for now we need to find another way to call the function.

Going low-level

One solution would be to write a small C++ DLL which merely forwards the call on. In other words, the C++ DLL is acting as a proxy for our intended function. The downside is that a new C++ DLL would have to be created every time a different DLL function needs to be called. The proxy function needs the exact number of parameters that the real function takes. Every C# programmer needs to know C++ to be able to do this.

A much better solution is to write a small, reusable DLL in x86 assembly language which can forward function calls to any location. This is trivial to write if we know a bit about how Win32 DLLs are called. All DLLs are called using the stdcall calling convention. This means that parameters are pushed onto the stack beginning at the right-most parameter. Thus, the first in the parameter list will be at the top of the stack. The return address is then placed on the stack and control is transferred to the callee. It is the callee's responsibility to pop all the parameters off the stack and not fiddle with more registers than absolutely necessary.

Consider the following function declaration:

[DllImport("Invoke", CharSet=CharSet.Unicode)]
public extern static int InvokeFunc(int funcptr, int hwnd, 
                                    string message, string title, int flags);
It is implemented in a DLL called Invoke.dll and has the export name InvokeFunc. It also takes five parameters, of which the last four are the exact parameters taken by the MessageBox() function. The first parameter is an address of a function. We will leave the implementation of InvokeFunc for now and look at code which can call this.
int hmod=LoadLibrary("User32");
int funcaddr=GetProcAddress(hmod, "MessageBoxW");
int result=InvokeFunc(funcaddr, 0, "Hello World", 
                      ".Net dynamic export invocation", 1 /*MB_OKCANCEL*/);
Console.WriteLine("Result of invocation is " + result);

FreeLibrary(hmod);
This code loads the DLL into our process space, finds the address of a function we wish to call, then uses our special InvokeFunc() function to call a function through a function pointer.

Screenshot of Dependency Walker watching this taking place

In the screenshot above, notice how GetProcAddress() is being used to find the address of GetProcAddress()! This is because PInvoke uses GetProcAddress to find the address of any function specified by the DllImport attribute.

InvokeFunc Implementation

As we discussed earlier, the stdcall calling conventions places parameters onto the stack in reverse order. Thus, our function pointer will be at the top of the stack because it is first in the parameter list. If we can take this parameter off the stack, then jump to that location in memory, it would be the equivalent of calling that function without the intermediate proxy function.

The following fragment of x86 assembler achieves this

pop ecx		; save return address
pop edx		; Get function pointer
push ecx	; Restore return address
jmp edx		; Transfer control to the function pointer
Because we've used a jmp instruction rather than a call instruction, control will be transferred directly from the called function back to the CLR, passing any return value directly back.

Conclusion

Everything needed to compile and run this code is included with Visual Studio .Net. The x86 DLL built can be reused for calling any function pointer, not just a function with a specific signature and is only 2,560 bytes.

It turns out that if you are not running .Net on Windows XP, there is a DLL with an equivalent proxy function to the one we built. That DLL is msjava.dll, which of course is missing from Windows XP due to the Microsoft-Sun agreement on Java technology. msjava.dll provides an export with the name call() which duplicates this functionality.

License

This article, along with any associated source code and files, is licensed under The BSD License

About the Author

Richard Birkby
Web Developer
United Kingdom United Kingdom
Member
Richard Birkby is a software engineer from London, UK, specializing in .Net. Richard has coded for many different sized companies from small venture-capital funded start-ups, to multi-national corporations (ie Microsoft). When he's not programming, he enjoys driving his sports car or eating curry (although never at the same time!).
 
Richard helps run CurryPages.com and has several other covert ventures in development. Stay tuned!

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionLoading unmanaged DLL from memorymemberFlyersWeb5 Nov '12 - 10:19 
Hi,
 
Very interesting article and comment. I'm currently working on a similar issue but I want to load and execute a DLL from memory.
 
I intended to do so like that :
 
public unsafe void LaunchWindowedProgramInMemory(Stream s)
{
	BinaryReader br = new BinaryReader(s);
	br.BaseStream.Position = 0;
 
	byte[] bin = br.ReadBytes((int)s.Length);
	try
	{
		fixed (byte* p = bin)
		{
			IntPtr ptr = (IntPtr)p;
 
			IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(ptr, "MultiplyByTen");
			if (pAddressOfFunctionToCall == IntPtr.Zero) return;
 
			MultiplyByTen multiplyByTen = (MultiplyByTen)Marshal.GetDelegateForFunctionPointer(																						                                       
                              pAddressOfFunctionToCall,																					
                              typeof(MultiplyByTen)
                        );
			int theResult = multiplyByTen(10);
			Console.WriteLine(theResult);
		}
 
	}
	catch (Exception e)
	{
		Console.Write(e.ToString());
	}
}
 
This is for personal experiments and for studies so my DLL is very simple, I've taken the same as in preceding comment :
 
extern "C" __declspec(dllexport) int MultiplyByTen(int numberToMultiply);
 
int MultiplyByTen(int numberToMultiply)
{
        int returnValue = numberToMultiply * 10;
        return returnValue;
}
 
The problem is that when I call GetProcAddress I always got a 0x00 address return. If someone has an idea of why I got this... Thanks Smile | :)
SuggestionDynamically calling an unmanaged dll from .NET (C#)memberDamavand2 Mar '12 - 4:08 
Dynamically calling an unmanaged dll from .NET (C#) by JonathanSwift
 
This sample is in response to a question left on my previous post, namely how to call an unmanaged dll from managed code when the dll in question isn't known until runtime (for instance, the path is stored in the registry, or an xml file, etc etc).
 
Apologies if this sample seems a little hurried, but I have another presentation to write and so time is short!
 
So let's begin.
 
To start and to refresh our memories, let's create a very basic C++ dll that does very little..... your code should resemble the following (check out my previous post for more info on this):
 
Header file
extern "C" __declspec(dllexport) int MultiplyByTen(int numberToMultiply);
 
Source code file
#include "DynamicDLLToCall.h"

int MultiplyByTen(int numberToMultiply)
{
        int returnValue = numberToMultiply * 10;
        return returnValue;
} 
As you can probably infer from the function name, an int is passed into this function and it will return the number passed in multiplied by ten. Told you it would be simple.
 
Now comes the more interesting part, actually calling this dll dynamically from your C# source code. There are two Win32 functions that are going to help us do this:
 
1) LoadLibrary - returns a handle to the dll in question
2) GetProcAddress - obtain the address of an exported function within the previously loaded dll
 
The rest is rather simple. We use LoadLibrary and GetProcAddress to get the address of the function within the dll we want to call, and then we use the GetDelegateForFunctionPointer static method within the Marshal class to assign this address to a C# delegate that we define. Take a look at the following C# code:
 
static class NativeMethods
{
        [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);
}
 
class Program
{
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        private delegate int MultiplyByTen(int numberToMultiply);
 
        static void Main(string[] args)
        {
                IntPtr pDll = NativeMethods.LoadLibrary(@"PathToYourDll.DLL");
                //oh dear, error handling here
                //if (pDll == IntPtr.Zero)

                IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "MultiplyByTen");
                //oh dear, error handling here
                //if(pAddressOfFunctionToCall == IntPtr.Zero)

                MultiplyByTen multiplyByTen = (MultiplyByTen)Marshal.GetDelegateForFunctionPointer(
                                                                                        pAddressOfFunctionToCall,
                                                                                        typeof(MultiplyByTen));
 
                int theResult = multiplyByTen(10);
 
                bool result = NativeMethods.FreeLibrary(pDll);
                //remaining code here

                Console.WriteLine(theResult);
        }
} 
 
The only item worthy of note is the UnmanagedFunctionPointer attribute, which was introduced to version 2.0 of the .NET framework, check out the docs online for more information.
 
Hope this helps.
GeneralRe: Dynamically calling an unmanaged dll from .NET (C#)memberRichard Birkby2 Mar '12 - 6:09 
My CodeProject article was written in 2001. This was before .Net 2 and the rather useful GetDelegateForFunctionPoint method was introduced. Had that method been around 11 years ago, it's very unlikely I'd have written this article.
QuestionI had to change the makefile a bit to path to Csc.exememberdcarl66117 Aug '11 - 6:19 
c:\WINDOWS\Microsoft.NET\Framework\v3.5\Csc.exe $**
GeneralLoading User dllsmemberDebojyoti Majumder14 Jan '11 - 1:46 
I have some dll's which are created from Visual C++.
I want to them load from C# application.
 
I have tried by giving the full path name to the Dllimport but I didn't worked.
I have put them in C:\Windows\System32 then they worked.
 
However, I guess this is how things should not be working.
What should I do??
QuestionCreate invoke.dll on 64-bit machinesmemberAlexander Pikus3 Oct '10 - 3:58 
How can I create invoke.dll on 64-bit machines, since NMAKE is supported only on 32-bit machines?
 
Thanks a lot
GeneralDon't do this any morememberMoxxis7 Jun '10 - 8:42 
Back in wacky 2001, this was all cool and macho. Now we have
 
System::Runtime::InteropServices::Marshal::GetDelegateForFunctionPointer
 
which is there for just this purpose. It will take an intenger (actually, IntPtr) and convert it to a delegate you can call from C#. "No assembly required. (TM)"
Questionwithout asm?memberUnruled Boy18 Dec '09 - 1:59 
is there a way out without using asm, just pass: dll file, function name, argument list, and it goes?
 
and, your asm way is not really dynamic, it only works for the MessageBox api, not all dlls.
 
Regards,
unruledboy_at_gmail_dot_com
http://www.xnlab.com

GeneralEasy way (.Net Marshaling)memberJonyRocketCZ25 Nov '09 - 3:42 
This c# call function from dll. You only need to know types op parameters and type od return value.
I have 2 strings and result is also string.
 


 
using System.Runtime.InteropServices;
 
...
 
[DllImport("kernel32")]
private extern static int LoadLibrary(string lpLibFileName);
[DllImport("kernel32")]
private extern static bool FreeLibrary(int hLibModule);
[DllImport("kernel32", CharSet = CharSet.Ansi)]
private extern static int GetProcAddress(int hModule, string lpProcName);
private delegate String myMethodDelegate( string func_dataarg, string func_cfgarg);
private string SharpDllcall(string dll_name, string func_name, string func_dataarg, string func_cfgarg)
{
if (dll_name == null) return "ERROR - null dll_name";
if (dll_name == "") return "ERROR - empty dll_name";
if (func_name == null) return "ERROR - null func_name";
if (func_name == "") return "ERROR - empty func_name";
 
int dllhnd = 0;
int funchnd = 0;
int stateSucess = 0;
try
{
dllhnd = LoadLibrary(dll_name);
if (dllhnd == 0) throw new Exception();
stateSucess = 1;
funchnd = GetProcAddress(dllhnd, func_name);
if (funchnd == 0) throw new Exception();
stateSucess = 2;
myMethodDelegate myDelegate;
myDelegate = (myMethodDelegate)Marshal.GetDelegateForFunctionPointer
((IntPtr)funchnd, typeof(myMethodDelegate));
stateSucess = 3;
return myDelegate(func_dataarg, func_cfgarg);
}
catch
{
switch (stateSucess)
{
case 0: return "ERROR - error loading library";
case 1: return "ERROR - error calling function";
case 2: return "ERROR - error creating sharp delegate";
default: return "ERROR - error inside function";
}
}
finally
{
if (dllhnd != 0) FreeLibrary(dllhnd);
}
}

GeneralRe: Easy way (.Net Marshaling)memberRichard Birkby25 Nov '09 - 3:49 
Thanks for this.
 
See also the following comment: Late binding on native DLLs with C#[^]
GeneralRe: Easy way (.Net Marshaling)memberUnruled Boy18 Dec '09 - 1:58 
if you know the arguments and define the delegate, why bother late binding? why not just dllimport?
 
Regards,
unruledboy_at_gmail_dot_com
http://www.xnlab.com

Questioncall fun when not add referencesmemberhuuchau8419 Mar '09 - 19:07 
I have a lybrary:
namespace LBR
{
public class class1
{
public string getstr(string _str)
{
return _str + "test ok";
}
}
}
Buil:--> "LBR.DLL"
Creat a new project
not add reference file LBR.DLL to Bin, I copy LBR.DLL to "C:\\LBR.DLL". can i call fun getstr() in class "class1"???? Confused | :confused:
thanks!!!!!!
AnswerExcellent articlememberdefconhaya7 Mar '09 - 4:03 
Very useful stuff.
In order to make Invoke.dll you'll need MASM32 from here http://www.masm32.com/masmdl.htm[^] and run those commands:
d:\masm32\bin\ml.exe /c /coff /Cp /Fl /Sc /Sg Invoke.asm
d:\masm32\bin\link.exe -DLL -entry:DllMain /machine:i386 /subsystem:windows /out:Invoke.dll /export:InvokeFunc Invoke.obj

GeneralDynamicly load a DLL functionsmemberMember 453941111 Feb '09 - 6:41 
hello,
I'm searching for a way to call a function that i load dynamicly.
In my DLL are the functions CreateForms();ShowForms();CloseForms();
It's should be like I load ones my dll and afther that I call functies from that
DLL from a button. But how can you to that??
QuestionLINK: error LNK2001: unresolved external symbol _DLLMainmembernate alwine12 Nov '08 - 11:33 
Hi I am trying to build your project but am having issues linking Invoke.obj. When I try to execute
 
D:\Documents and Settings\208047355.GESMAM\My Documents\codeproject\loadlibrary\
article_src>link /DLL /entry:DLLMain /machine:i386 /subsystem:windows /out:Invok
e.dll /export:InvokeFunc Invoke.obj
 

it is returning the following error:
 
Microsoft (R) Incremental Linker Version 7.10.6030
Copyright (C) Microsoft Corporation. All rights reserved.
 
Creating library Invoke.lib and object Invoke.exp
Invoke.dll : warning LNK4086: entrypoint '_DLLMain' is not __stdcall with 12 byt
es of arguments; image may not run
LINK : error LNK2001: unresolved external symbol _DLLMain
Invoke.dll : fatal error LNK1120: 1 unresolved externals
 

Any idea how I fix this?
 
Thanks
Nate
QuestionDLLImportmembergclopes18 Sep '08 - 7:24 
I have a DLL in C++ and I want to use a function but in an application in C#.
 
The header of the function in C++ is:
 
__declspec(dllexport) short DLGet(LPSTR VarName, LPVOID Destination, LPSTR Format)
 
The second parameter is returned from the function.
 
What I want to know is How to pass those parameters to that function in my C# application?
 
I would be very appreciated if someone could help.
 
Thank you
 
GCLopes
QuestionHow to compile code written in assembler language?memberMember 6628769 Jul '08 - 22:19 
How to compile code written in assembler language?
GeneralIs it possible to elevate this process for Vistamemberyincekara11 Jun '08 - 6:12 
I am invoking a function from a 3'rd party dll. It works fine by using this method you 've mentioned in your article on XP. Also on Vista if UAC is disabled it works fine too. But if UAC is turned on method cannot work and returns an error code. How can we give appropriate rights do that InvokeFunc which is dynamically loaded into memory?
GeneralCompile time linking of dllmemberharsh290414 Apr '08 - 22:31 
Can I make an executable with a particular dll including in it?
I mean linking a dll at compile time only. So that I can run that exe from anywhere without having dll anywhere.
GeneralRe: Compile time linking of dllmemberMike_Silver_A2 Oct '08 - 0:53 
You can try to unpack a dll in memory, process relocations and so on. Also I find the following solution: boxedapp, it allows to load a dll from memory as it's really exists. seems what's you need.
 
hope this helps.
 
best, Mike
QuestionWhere i can find "Invoke.dll"?membertropot28 Jun '07 - 22:20 
Hi,
See the subject.
Best regards, Eugen.
AnswerRe: Where i can find "Invoke.dll"?memberRichard Birkby28 Jun '07 - 22:37 
The makefile gives the game away...
 

Invoke.obj: Invoke.asm
ml $(MLFLAGS) $**
Invoke.dll: Invoke.obj
link $** -DLL -entry:DllMain /machine:i386 /subsystem:windows /out:Invoke.dll /export:InvokeFunc

GeneralRe: Where i can find "Invoke.dll"?membertropot29 Jun '07 - 0:52 
Laugh | :laugh:
thanks,... silly me
GeneralRe: Where i can find "Invoke.dll"?memberdark_hunter6 Aug '07 - 13:09 
hola, no se mucho de esto asi que si me pudiera explicar un poco mas como obtener la dll o como hago funcionar este ejemplo te lo agradeceria mucho..
 
Gracias
 
salu2
 
x

GeneralRe: Where i can find "Invoke.dll"?memberkandy_soliton22 Aug '07 - 18:44 
HI Richard,
 
I don't understand the way the invoke.dll is created.
Can anyone explain the way it can be done?
 
Regards
kandy.

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 13 Nov 2001
Article Copyright 2001 by Richard Birkby
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid