本文内容
- 从非托管代码调用托管代码
- 平台调用的原生成
- 本机库加载
- 非托管调用约定
P/Invoke 是可用于从托管代码访问非托管库中的结构、回调和函数的一种技术。 大多数 P/Invoke API 包含在以下两个命名空间中:System
和 System.Runtime.InteropServices
。 使用这两个命名空间可提供用于描述如何与本机组件通信的工具。
我们从最常见的示例着手。该示例在托管代码中调用非托管函数。 让我们从命令行应用程序显示一个消息框:
using System;
using System.Runtime.InteropServices;
public class Program
{
// Import user32.dll (containing the function we need) and define
// the method corresponding to the native function.
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType);
public static void Main(string[] args)
{
// Invoke the function as a regular managed method.
MessageBox(IntPtr.Zero, "Command-line message box", "Attention!", 0);
}
}
上述示例非常简单,但确实演示了从托管代码调用非托管函数所需执行的操作。 让我们逐步分析该示例:
- 第 2 行显示
System.Runtime.InteropServices
命名空间(用于保存全部所需项)的 using 语句。 - 第 8 行引入
DllImport
属性。 此属性将告诉运行时应该加载非托管 DLL。 传入的字符串是目标函数所在的 DLL。 此外,它还指定哪些字符集用于封送字符串。 最后,它指定此函数调用 SetLastError,且运行时应捕获相应错误代码,以便用户能够通过 Marshal.GetLastWin32Error() 检索它。 - 第 9 行显示了 P/Invoke 的关键作用。 它定义了一个托管方法,该方法的签名与非托管方法完全相同。 可以看到,声明中包含一个新关键字
extern
,告诉运行时这是一个外部方法。调用该方法时,运行时应在DllImport
特性中指定的 DLL 内查找该方法。
该示例的剩余部分无非就是调用该方法,就像调用其他任何托管方法一样。
在 macOS 上也可以使用类似的示例。 需要更改 DllImport
属性中的库名称,因为 macOS 使用不同的方案来命名动态库。 下面的示例使用 getpid(2)
函数获取应用程序的进程 ID,然后控制台上列显该 ID:
using System;
using System.Runtime.InteropServices;
namespace PInvokeSamples
{
public static class Program
{
// Import the libSystem shared library and define the method
// corresponding to the native function.
[DllImport("libSystem.dylib")]
private static extern int getpid();
public static void Main(string[] args)
{
// Invoke the function and get the process ID.
int pid = getpid();
Console.WriteLine(pid);
}
}
}
它在 Linux 上也是类似的。 函数名称相同,因为 getpid(2)
是标准 POSIX 系统调用。
using System;
using System.Runtime.InteropServices;
namespace PInvokeSamples
{
public static class Program
{
// Import the libc shared library and define the method
// corresponding to the native function.
[DllImport("libc.so.6")]
private static extern int getpid();
public static void Main(string[] args)
{
// Invoke the function and get the process ID.
int pid = getpid();
Console.WriteLine(pid);
}
}
}
1、从非托管代码调用托管代码
运行时允许通信流量双向流通,这样,便可以使用函数指针从本机函数回调托管代码。 在托管代码中,与函数指针最接近的功能就是委托,正是凭借这个功能,才能从本机代码回调托管代码。
此功能的使用方式类似于上面所述的从托管代码调用本机进程。 对于给定的回调,需要定义一个与签名匹配的委托,并将其传入外部方法。 运行时将负责处理所有剩余工作。
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
public static class Program
{
// Define a delegate that corresponds to the unmanaged function.
private delegate bool EnumWC(Int