P/Invoke是C#调用非托管代码的机制,通过DllImport声明外部方法,如调用MessageBox或GetSystemInfo,需注意参数类型映射、结构体布局及字符串编码,推荐使用pinvoke.net等工具辅助开发。

P/Invoke(Platform Invocation Services)是C#中用于调用非托管代码(如Win32 API、C/C++编写的DLL)的一种机制。它允许托管代码与本地系统库进行交互,比如调用Windows操作系统提供的API函数。
using System;
using System.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}");
}
以上就是C#的P/Invoke是什么?如何调用本地Win32 API?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号