P/Invoke

It is possible, though generally undesirable, to invoke unmanaged code from within C#. The .NET platform invoke facility (P/Invoke) was originally intended only to provide access to the Windows API, but you can use it to expose functions in any DLL.

To see how this works, let’s revisit Example 21-3. You will recall that you used the Stream class to rename files by invoking the MoveTo( ) method:

file.MoveTo(fullName + ".bak");

You can accomplish the same thing by using Windows’ kernel32.dll and invoking the MoveFiles method. To do so, you need to declare 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 class is used to indicate that an unmanaged method will be invoked through P/Invoke. The parameters are:

EntryPoint

Indicates the name of the DLL entry point (the method) to call.

ExactSpelling

Setting this to false allows matching of the entry-point name without case-sensitivity.

CharSet

Indicates how the string arguments to the method should be marshaled.

SetLastError

Setting this to true allows you to call GetLastError to check if an error occurred when invoking this method.

The rest of the code is virtually unchanged, except for the invocation of the MoveFile( ) method itself. Notice that MoveFile( ) is declared to be a static method of the ...

Get Programming C#, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.