gpt4 book ai didi

c# - 从托管代码引用非托管库,优点和缺点?

转载 作者:太空宇宙 更新时间:2023-11-04 01:42:20 25 4
gpt4 key购买 nike

大家好,

我想从我的 C# 代码中调用非托管库函数,如下所示。有两个选项,两者都有效。此时“Beep”函数很简单,没有输入/输出参数、指针、引用……我想知道在更复杂的情况下,这两种方法的优点和缺点是什么?

谢谢,米兰。

    [DllImport("kernel32.dll")]
public static extern bool Beep(uint iFreq, uint iDuration);
public void TestBeep()
{
Beep(300, 3000);
}

    internal delegate bool DelegBeep(uint iFreq, uint iDuration);
[DllImport("kernel32.dll")]
internal static extern IntPtr LoadLibrary(String dllname);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetProcAddress(IntPtr hModule, String procName);
public void BeepIt()
{
IntPtr kernel32 = LoadLibrary("Kernel32.dll");
IntPtr procBeep = GetProcAddress(kernel32, "Beep");
DelegBeep delegBeep = Marshal.GetDelegateForFunctionPointer(procBeep, typeof(DelegBeep)) as DelegBeep;
delegBeep(50, 1000);//Hz,ms
}

最佳答案

你的第二个比第一个复杂得多,但在这种情况下实现了同样的事情。

如果 DLL 的名称和函数的名称在编译时已知,则坚持使用第一种方法。如果您直到运行时才知道 DLL 和/或函数的名称,那么 LoadLibary/GetProcAddress 方法是您唯一的选择。

关于c# - 从托管代码引用非托管库,优点和缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3166797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com