Platform Invocation Services


Finally, depending on the lifetime of the application or component, it is quite possible that some pieces and components have been developed in Win32-based DLLs. Platform Invocation Services provides interoperability at the platform-level DLLs, giving the capability to a .NET developer to invoke functions exposed in legacy DLLs. Platform Invocation Services, better known as PInvoke, provide the capability for .NET applications to utilize functionalities exposed as Win32 DLLs. This includes the DLL functions that are exposed by Microsoft and any other third-party or home-grown DLLs. Unlike utilizing COM components in .NET applications, the process of using platform APIs is a bit tedious and involves manual creation of a function definition. For instance, consider the Win32 API to get the computer's name, GetComputerName, which returns the name of the current computer. (This example is being used for illustration of the concept; the .NET Framework already provides this functionality through a .NET Framework class.)

Fortunately, Adam Nathan's .NET and COM: The Complete Interoperability Guide (ISBN: 0-672-32170-X) serves as a lifesaver because he has already done the job of providing the function definitions of a number of commonly used Windows DLLs.

 
 Imports System.Text Module Module1   Public Declare Sub GetComputerName Lib "kernel32" Alias "GetComputerNameA" _      (ByVal lpBuffer As StringBuilder, ByRef nSize As Integer)     Sub Main()         Dim size As Integer = 20         Dim buffer As StringBuilder = New StringBuilder(size)         GetComputerName(buffer, size)         Console.WriteLine(buffer)     End Sub End Module 

PInvoke can be used with Visual C# as well:

 
 using System; using System.Text; using System.Runtime.InteropServices; namespace ConsoleApplication1 {    class Class1    {       [DllImport("kernel32.dll")]       static extern bool GetComputerName(                     [Out] StringBuilder lpBuffer, ref uint lpnSize);       [STAThread]       static void Main(string[] args)       {          uint size = 20;          StringBuilder buffer = new StringBuilder((int) size);          GetComputerName(buffer,ref size);          Console.WriteLine(buffer.ToString());       }    } } 

If you are developing .NET applications using C++, it makes more sense to use the API directly from C++ without using any PInvoke facilities.



Microsoft.Net Kick Start
Microsoft .NET Kick Start
ISBN: 0672325748
EAN: 2147483647
Year: 2003
Pages: 195
Authors: Hitesh Seth

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net