- Get link
- X
- Other Apps
Posted by
Real
- Get link
- X
- Other Apps
Developers creating the application using .Net framework are managed code and it will be executed by CLR(common language runtime). Whereas unmanaged codes are source code generated by WIN32 APIs, valuable external libraries, COM components, and COM+ services. To call a functions located in an unmanaged dll using .net canbe done using technique is called as PInvoke.
When platform invoke calls an unmanaged function it firstly locates the DLL containing the function and then loads it into memory. It searches for the function in memory and locates its memory address. After that it pushes the function arguments into the stake and marshaling data as required. Finally the control is transferred to the unmanaged function. Platform invoke throws exceptions generated by the unmanaged function to the managed caller.
Example:
Let us create a sample application which will call the message box from one of WIN32 API called "user32.dll". WIN32 APIs may contain two versions for each function that handles characters and strings. One for the ANSI version (MessageBoxA), and the other for the Unicode version (MessageBoxW).
Step1 :
Create the wrapping class for unmanaged dll functions, this classwill allows the pinvoke to handle the underlying exported functions automatically. We need to define a static method for each DLL function we want to call. Below class "Unmanaged" defines a static method for calling "MessageBox"
Imports System.Runtime.InteropServices
Public Class Unmanaged
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
Step 2:
Let us create a sample windows application to consume the unmanaged function in our application.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
Unmanaged.MessageBox(0, "Hello world!!!", "PInvoke example", 0)
End Sub
End Class
Step 3:
Output
Comments
Post a Comment
Thanking you for the comment.