【发布时间】:2019-04-17 03:15:26
【问题描述】:
我正在从 C# 调用一些非托管 C 函数(在外部 dll 中)。我有 2 种不同的方法可以做到这一点,我不确定 2 之间的区别(除了代码量)
方法#1
[DllImport("PComm32.dll",CallingConvention=CallingConvention.StdCall, EntryPoint ="PmacSelect")]
public static extern int PmacSelect(IntPtr intPtr);
int device = PmacSelect(IntPrt.Zero);
方法#2
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int PmacSelect(IntPrt intptr);
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
public PmacSelect PmacSelectFunction;
private IntPtr pDll = LoadLibrary("PComm32");
IntPtr pAddressOfFunctionToCall = GetProcAddress(pDll, "PmacSelect"); //find the function in the loaded pcomm32 dll
PmacSelectFunction = (PmacSelect)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall,type(PmacSelect));
int device = PmacSelectFunction(IntPrt.Zero);
这两种方法都有效,并调用位于 PComm32.dll 文件中的 PmacSelect 函数。 我的问题是这两种方法之间的功能差异是什么? 方法#1 必须依赖 Windows 在后台根据需要为我管理 DLL? Windows 可以在我不知情的情况下加载和卸载 dll 吗?我真的不在乎它是否这样做,只要它在我调用 dll 中的函数时自动加载。
方法 #2 当我调用 LoadLibrary 时,DLL 被显式加载。库在我释放之前是否保留在内存中?
【问题讨论】:
-
stackoverflow.com/questions/2445536/… 可能被骗(答案告诉你原因)