Platform Invocation


If you were to immediately start using the WIN32 API or any of the native C++ data types within your managed application, you would lose the benefits the .NET Framework provides. Although you are certainly free to mix unmanaged and managed code together, doing so can lead to future problems, such as frequent data type conversions, which you may need to perform as your code executes in and out of the common language runtime. If you still want to execute your code within a managed environment while still retaining the ability to call unmanaged dynamic link library functions, you can use a method known as Platform Invocation, otherwise known as P/Invoke.

P/Invoke provides the ability to call unmanaged DLL functions using managed code. As you'll recall from the last hour, the runtime callable wrapper (RCW) and the COM callable wrapper (CCW) enable communication between COM and .NET objects by marshaling data back and forth between the objects without the developer needing to worry about data type conversions, unless there's no comparable data type in one of those objects. In much the same way, the P/Invoke service is responsible for locating the entry points within a dynamic link library, and once an entry point is found, P/Invoke marshals the parameters and return values between the managed client and the unmanaged DLL function.

The first step in calling a DLL function from managed code involves the use of the DLLImport attribute. Thankfully, using this attribute means you don't have to worry about loading the DLL dynamically and using the WIN32 API function GetProcAddress to find the appropriate function. This is all handled for you by using P/Invoke.


Sams Teach Yourself Visual C++. NET in 24 Hours
Sams Teach Yourself Visual C++.NET in 24 Hours
ISBN: 0672323230
EAN: 2147483647
Year: 2002
Pages: 237

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: