Take reference or Import Unmanaged DLL into application

Kailash Chandra Behera | Friday, December 29, 2017

Introduction

Sometimes we are working with external devices like printer, scanner, barcoad scanner etc. in our application.

For interacting with above mentioned devices, you need take references of drivers. But most of cases you will not found DLLs as managed and you cannot take reference of unmanaged DLLs using 'Add Reference Feature' of visual Studio.

This blog describes how to get reference of unmanaged DLLs in C#.

Getting Started

.NET Framework provides 'DllImportAttribute' class(which comes under System.Runtime.InteropServices namespace and mscorlib DLL) for taking reference of unmanaged DLLs. You can apply this attribute to methods for taking reference of unmanaged DLL.

The DllImportAttribute attribute provides the information needed to call a function exported from an unmanaged DLL. As a minimum requirement, you must supply the name of the DLL containing the entry point.

The following code example shows how to use the DllImportAttribute attribute to import the unmanaged DLL. The code example then calls the imported method.

The 'user32.dll' is an unmanaged DLL as it not written in .NET Framework languages, this example imports the 'user32.dll' to use its Win32 MessageBox function.

Code Example

 using System;  
 using System.Runtime.InteropServices;  
 class DllImportExample  
 {  
   // Use DllImport to import the Win32 MessageBox function.  
   [DllImport("user32.dll", CharSet = CharSet.Unicode)]  
   public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);  
   static void Main()  
   {  
     // Call the MessageBox function using platform invoke.  
     MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);  
   }  
 }  
Note:- Make sure dll name must be with full path, here above example the user32.dll is in Debug folder.

Thanks