[Sample of May 3rd] C# app dynamically loads a native DLL

 

Homepage image
Sample of the Day RSS Feed

Sample Downloads: https://code.msdn.microsoft.com/CSLoadLibrary-4f25687f

Today’s sample demonstrates dynamically load a native DLL by P/Invoking LoadLibrary, and invoke its exported functions.

imageYou can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage https://1code.codeplex.com/.

 

Introduction

CSLoadLibrary in C# mimics the behavior of CppLoadLibrary to dynamically load a native DLL (LoadLibrary) get the address of a function in the export  table (GetProcAddress, Marshal.GetDelegateForFunctionPointer), and call it.

The technology is called Dynamic P/Invoke. It serves as a supplement for the P/Invoke technique and is useful especially when the target DLL is not in the search path of P/Invoke. If you use P/Invoke, CLR will search the dll in your assembly's directory first, then search the dll in directories listed in PATH environment variable. If the dll is not in any of those directories, you have to use the so called Dynamic PInvoke technique that is demonstrated in this code sample.

Implementation

1. P/Invoke the API LoadLibrary to dynamically load a native DLL.

2. P/Invoke the API GetProcAddress to get the function pointer of a specified function in the DLL's export table.

3. Call Marshal.GetDelegateForFunctionPointer to convert the function pointer to a delegate object.

4. Call the delegate.

5. Call FreeLibrary on the unmanaged dll. (Be careful of calling kernel32!FreeLibrary from managed code! This is unsafe and can crash if done wrong.)

 

More Information

�� Type-safe Managed wrappers for kernel32!GetProcAddress

�� Dynamic PInvoke

�� MSDN: Exporting from a DLL

�� MSDN: Exporting from a DLL Using DEF Files

�� MSDN: Exporting from a DLL Using __declspec(dllexport)

�� MSDN: Creating and Using a Dynamic Link Library (C++)

�� HOWTO: How To Export Data from a DLL or an Application

�� Dynamic-link library