Calling unmanaged function from within managed code


Calling unmanaged function from within managed code When we use windows API in Dot Net?Is it managed or un managed code?

✍: Guest


Have you ever tried to called an unmanaged function (eg: MessageBox function inside the User32.dll ) with in a managed code? Let's try to do that.

Open up your Visual studio 2005 and create a new VB project. Add a new class and give an appropriate name. Import System.Runtime.InteropServices so that we will get interoperating services capability to our class. Now we have to identify the dll and the function which we are going to call. Mainly there are 3 commonly used WIN32 API's. GDI32.dll which is mainly used for graphic device interface (GDI), Kernel32.dll for low level operating system functions, and User32.dll for windows management functions for message handlings, timers, menus etc. Let's take User32.dll. Now how to know the functions inside this dll.

There is a visual tool shipped with the Visual Studio 2005 and called Microsoft dependency walker "Depends.exe". You can run this tool from "\Common7\Tools\Bin" directory under your Visual Studio directory. Just open User32.dll (which will be available in System32 folder under your windows directory) using dependency walker. You will get all the functions in the right pane of that tool. We have to create a class to hold the Dll function which is called as Wrapping. Wrapping the unmanaged DLL functions in a managed class allows the platform invoke to handle the underlying exported functions automatically. You have to define a static method for each DLL function you want to call. Next step is to create a prototype in managed code. To set the prototype we will use the "Declare" statement to define the function and the "Lib" keyword to identify its library name as in the following line of code.

Declare Auto Function MessageBox Lib "User32.dll"

Auto" keyword is set to let the target platform determines the suitable character width (ANSI or Unicode).Now you need to convert the unmanaged types of the function parameters to their managed counterparts. MSDN library provides a table that resolves each WIN32 API type into its managed type. You can get this table from here.

Now our managed code for MessageBox will look like this

Public Class Unmanged
Declare Auto Function MessageBox Lib "User32.dll" _
(ByVal Hwnd As Integer, ByVal Text As String, _
ByVal Caption As String, ByVal Type As Integer) _
As Integer
End Class

Now you can call this function from any of your forms like this

Unmanged.MessageBox(0, "Hii", "Calling Unmanged function Example", 0)

Examine Running Processes Using Both Managed and Unmanaged Code:

2009-03-06, 5102👍, 0💬