C#呼叫C++ dll的兩種方法
阿新 • • 發佈:2019-02-15
靜態呼叫
[DllImport(@"xxx.dll", EntryPoint = "TestMethod")]
static extern string TestMethod(string InParam);
string ret = TestMethod("hello");
動態呼叫
[DllImport("Kernel32.dll")]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll" )]
public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
private static IntPtr instance;//dll例項
public delegate string DlTestMethod(string InParam);//呼叫方法的委託
/// <summary>
/// 載入DLL
/// </summary>
/// <param name="dllPath"></param>
public static void LoadLib(string dllPath)
{
instance = LoadLibrary(dllPath);
if (instance == IntPtr.Zero)
{
Console.WriteLine("載入dll失敗!" );
}
}
/// <summary>
/// 獲取方法指標
/// </summary>
/// <param name="functionName"></param>
/// <param name="t"></param>
/// <returns></returns>
private static Delegate GetAddress(string functionName, Type t)
{
IntPtr addr = GetProcAddress(instance, functionName);
if (addr == IntPtr.Zero)
return null;
else
return (Delegate)Marshal.GetDelegateForFunctionPointer(addr, t);
}
/// <summary>
/// 釋放dlll
/// </summary>
public static void FreeLib()
{
FreeLibrary(instance);
}
LoadLib(@"xxx.dll");
DlTestMethod funcTestMethod = (DlTestMethod)GetAddress("TestMethod", typeof(DlTestMethod));
string ret = funcTestMethod("hello");
FreeLib();
總結
靜態呼叫:呼叫方式簡單,可滿足通常的要求;被呼叫的dll會在程式載入時一起載入到記憶體中;如果在程式資料夾中沒有dll檔案,程式會報錯。
動態呼叫:呼叫方式複雜,需藉助於API函式來完成dll的載入,解除安裝及方法呼叫;能更加有效地使用記憶體,多在大型應用程式中使用;如果在程式資料夾中沒有dll檔案,也可以是程式不報錯。