

新闻资讯
技术学院P/Invoke是C#调用非托管代码的机制,通过DllImport声明外部方法,如调用MessageBox或GetSystemInfo,需注意参数类型映射、结构体布局及字符串编码,推荐使用pinvoke.net等工具辅助开发。
P/Invoke(Platform Invocation Services)是C#中用于调用非托管代码(如Win32 API、C/C++编写的DLL)的一种机制。它允许托管代码与本地系统库进行交互,比如调用Windows操作系统提供的API函数。
using System; using Syste说明:m.Runtime.InteropServices; class Program { // 声明外部方法 [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType); static void Main() { MessageBox(IntPtr.Zero, "Hello from C#!", "Greeting", 0); } }
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEM_INFO
{
public ushort processorArchitecture;
private ushort reserved;
public uint pageSize;
public IntPtr minimumApplicationAddress;
public IntPtr maximumApplicationAddress;
public IntPtr activeProcessorMask;
public uint numberOfProcessors;
public uint processorType;
public uint allocationGranularity;
public uint processorLevel;
public uint processorRevision;
}
[DllImport("kernel32.dll")]
static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
static void Main()
{
GetSystemInfo(out SYSTEM_INFO sysInfo);
Console.WriteLine($"处理器数量: {sysInfo.numberOfProcessors}");
}