Take reference or Import Unmanaged DLL into application

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

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

نموذج الاتصال