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 from Chapter 21. 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’
kernal32.dll and invoking the
MoveFiles method. To do so, you need to declare
the method as a static
extern
and you need to 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
DllImportAttribute
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 be called.
-
ExactSpelling Setting this to
falseallows 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
trueallows you to callGetLastErrorto 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 ...