【发布时间】:2012-04-12 11:07:07
【问题描述】:
如何直接调用从 DLL 导出的本机函数?谁能给我一个小例子?
【问题讨论】:
标签: c#
如何直接调用从 DLL 导出的本机函数?谁能给我一个小例子?
【问题讨论】:
标签: c#
class PlatformInvokeTest
{
[DllImport("msvcrt.dll")]
public static extern int puts(string c);
[DllImport("msvcrt.dll")]
internal static extern int _flushall();
public static void Main()
{
puts("Test");
_flushall();
}
}
如果您需要从本机 dll 生成 C# DLLImport 声明,请观看此帖子:Generate C# DLLImport declarations from a native dll
【讨论】:
取决于你到底想要什么......我的代码中有这样的东西,但它使用 Win32 API dll 的
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
然后打电话
GetForegroundWindow()
就像在类中定义的一样
【讨论】:
下面是DllImport 属性的一个简单示例:
using System.Runtime.InteropServices;
class C
{
[DllImport("user32.dll")]
public static extern int MessageBoxA(int h, string m, string c, int type);
public static int Main()
{
return MessageBoxA(0, "Hello World!", "Caption", 0);
}
}
此示例显示了声明在本机 DLL 中实现的 C# 方法的最低要求。方法C.MessageBoxA() 使用static 和external 修饰符声明,并具有DllImport 属性,它告诉编译器实现来自user32.dll,使用默认名称消息框A。
【讨论】: