O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

P/Invoke

COM components aren’t the only kind of unmanaged code you might need to work with. For example, you may sometimes want to call a Win32 API. With each new version of .NET, there has been less need to do this, because the framework class libraries provide .NET-friendly wrappers for more and more of the underlying services, but there are still a few places where it’s useful to use a Win32 API directly. We do this in C# using a feature called P/Invoke.

Note

The P is short for Platform, because this facility was originally intended only to provide access to the underlying platform API. In fact, you can use it to call functions in any DLL—it’s not limited to DLLs that are part of the Win32 API.

To see how this works, let’s look at a method offered by the Windows kernel32.dll library called MoveFile.[52] Unlike COM components, ordinary Win32 DLLs do not include enough metadata to describe fully the methods they offer—they’re designed to be called from C or C++, and the full descriptions live in header files provided as part of the Windows SDK. But the C# compiler doesn’t know how to read C header files, so we need to provide a complete description of the signature of the method we plan to use. We do this by declaring the method as a static extern and use the DllImport attribute:

[DllImport("kernel32.dll", EntryPoint="MoveFile",
 ExactSpelling=false, CharSet=CharSet.Unicode,
 SetLastError=true)]
static extern bool MoveFile(
 string sourceFile, string destinationFile);

The DllImport attribute ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required