C# 使用 DllImport 调用 Windows API 的 CloseHandle 函数
在 C# 中引用 Windows API 的 CloseHandle 函数,需要使用 DllImport 特性来导入 kernel32.dll,并定义 CloseHandle 函数的签名。
以下是一个示例代码:
using System;
using System.Runtime.InteropServices;
class Program
{
// 导入 CloseHandle 函数
[DllImport('kernel32.dll')]
public static extern bool CloseHandle(IntPtr hObject);
static void Main()
{
// 打开一个句柄,例如文件句柄、进程句柄等
IntPtr handle = /* 获取句柄 */;
// 调用 CloseHandle 函数关闭句柄
bool result = CloseHandle(handle);
if (result)
{
Console.WriteLine('句柄关闭成功');
}
else
{
Console.WriteLine('句柄关闭失败');
}
}
}
请注意,上述示例代码中的 /* 获取句柄 */ 处需要根据具体情况替换为获取句柄的代码。
原文地址: https://www.cveoy.top/t/topic/pdS0 著作权归作者所有。请勿转载和采集!