P/Invoke
1.P/Invoke是什么?有何作用?
2.简单的使用P/Invoke的demo
1.P/Invoke是什么?有何作用?
P/Invoke使得C#程序调用非托管的成为可能,例如可以使用P/Invoke来调用win32 api。
2.简单的使用P/Invoke的demo
2.1 使用P/Invoke直接调用win32 api
public class Program { /// <summary> /// import kernel32.dll /// </summary> /// <param name="source"></param> /// <param name="dest"></param> /// <returns></returns> [DllImport("kernel32.dll", EntryPoint = "MoveFile", ExactSpelling = false, CharSet = CharSet.Unicode, SetLastError = true)] static extern bool MoveFile(string source, string dest); static void Main(string[] args) { // Call P/Invoke string source = @"d:/test.txt"; string dest = @"d:/test.txt.bak"; if (UsingPInvoke.Program.MoveFile(source, dest) == true) { Console.WriteLine("Move File Ok!"); } else { Console.WriteLine("Move File Error!"); } } }
2.2 C#中的指针
public class UsingPointers { const uint GenericRead = 0x80000000; const uint OpenExisting = 3; const uint UseDefault = 0; int fileHandle; [DllImport("kernel32.dll", SetLastError = true)] static extern unsafe int CreateFile( string filename, uint desiredAccess, uint shareMode, uint attributes, uint createDisposition, uint flagsAndAttributes, uint templateFile ); [DllImport("kernel32.dll", SetLastError = true)] static extern unsafe bool ReadFile( int hFile, void* lpBuffer, int bBytesToRead, int* nBytesRead, int overlapped ); public UsingPointers(string filename) { this.fileHandle = CreateFile( filename, GenericRead, UseDefault, UseDefault, OpenExisting, UseDefault, UseDefault ); } public unsafe int Read(byte[] buffer, int index, int count) { int byteRead = 0; // 将byte[]转换成byte* fixed(byte* bytePointer = buffer) { // 调用win32函数 ReadFile( fileHandle, bytePointer + index, count, &byteRead, 0 ); } return byteRead; } }
注意编译时,需要更改项目属性:
本博客中的文章均是在学习和编码过程中的总结,其中难免存在错误之处,给您的带来的不便尽请谅解,同时欢迎您提出意见。