您的位置:首页 > 编程语言 > C语言/C++

C#调用C++ dll的两种方法

2015-10-24 16:57 726 查看
静态调用

[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文件,也可以是程序不报错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息