tutorial

Page 59

Declare is the statement to state the Win32 API functions located in the Win32 DLLs. And the respective arguments declared with CLR data type. In C#, we need to use the extern keyword with the attribute DLL Import to specify the Win32 DLL and the function should be declared as static function. using System; class PInvokeDemo { [dllimport("user32.dll")] public static extern int MessageBox(int hwnd, string msg, string caption, int type); public static int Main() { MessageBox(0, "Hello World!", "Tutorial", 1); return 0; } } In the above example MessageBox function is accessed from user32.dll by using the attribute DLL Import, and declared as static function Managed Types and Unmanaged Types We have seen how to call an unmanaged code in a managed code, now the question is how unmanaged code understands the managed data type and vice the versa. We will see how string will be sent from managed code and returned back to managed code. When passing a string value as an input argument to an unmanaged code CLR will take care of converting that to a native string type. When we try to call a function, which returns string then the managed code, has to allocate memory and send to the function in unmanaged code. For example if we want to retrieve the OS Temp path then we can call GetTempPath API function of “kernel32.dll�, Following code snippet shows how to call the function with string as an out argument with VB.NET. Imports System.Runtime.InteropServices Public Class Win32 Declare

Auto

Function

MessageBox

Lib

"user32.dll" (ByVal hWnd As Integer, _ ByVal

txt

As

String,

String, ByVal Typ As Integer) As Integer

ByVal

caption

As


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.