Some Other Interop Methods

Looking at the samples in Listings 7.1 to 7.4, you might notice the similarities between this method of interoperation and Visual Basic 6.0's Declare statement. You can achieve much of the same functionality as P/Invoke with the following VB 6 Declare statement:

Declare Function MessageBox Lib "user32" Alias "MessageBoxW"( hWnd As Long,
      txt As String, caption As String, Typ As Long) As Long

In fact, using Declare is still supported as a viable means to use old code with Visual Basic .NET. The old Declare and the new Declare still have issues that center around type safety; regardless, you can use Declare to interop with code that was not written in VB .NET.

Another means of interoperating with legacy code is to use the LoadLibrary API followed by a call to GetProcAddress. These two functions give a C/C++ program a means of loading a DLL and calling into the functions implemented in the DLL. These routines were originally developed to provide for binary interoperability. These routines are inherently type unsafe. Because they return what effectively is an address pointer, they cannot be used alone in a safe managed environment.

Note

A tool called depends was designed to show DLL dependency information about an executable or DLL. Depends is found in Program FilesMicrosoft Visual Studio .NETCommon7ToolsBin. This tool has a feature called profiling that tracks how DLLs are loaded into a process as it is running. If you run this tool on the executable that is generated from Listing 7.1 (calling an unmanaged MessageBox API), you get the following output:

LoadLibraryExW("f:user32.dll", 0x00000000, LOAD_WITH_ALTERED_SEARCH_PATH) called from
 "MSCORWKS.DLL" at address 0x791BDE66.
LoadLibraryExW("f:user32.dll", 0x00000000, LOAD_WITH_ALTERED_SEARCH_PATH) returned NULL.
 Error: The specified module could not be found (126).
LoadLibraryExW("user32.dll", 0x00000000, 0x00000000) called from "MSCORWKS.DLL" at address
 0x791BDE66.
LoadLibraryExW("user32.dll", 0x00000000, 0x00000000) returned 0x77D40000.
GetProcAddress(0x77D40000 [USER32.DLL], "MessageBox") called from "MSCORWKS.DLL" at
 address 0x791F2ECB and returned NULL. Error: The specified procedure could not be found (127).
GetProcAddress(0x77D40000 [USER32.DLL], "MessageBoxW") called from "MSCORWKS.DLL" at
 address 0x791F2F49 and returned 0x77D78839.

From this output, you can see that the CLR is essentially calling LoadLibrary and GetProcAddress as you do P/Invoke call.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.224.197