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

非常不错的C#动态调用DLL代码

2012-09-15 23:49 351 查看
一、新建一调用工程项目和一个要测试的类项目,首先设计好测试的类以及函数,然后编译生成对应的类名.DLL文件。然后复制到调用工程项目的BIN目录下。

二、在调用工程项目中新建一WINFORM窗体,工具箱中拉一个按钮到窗体,然后在按钮事件中写调用代码

//调用办法

private void button1_Click(object sender, EventArgs e)

{

//调用办法

DllManager myDllManager = new DllManager();

//输出结果

Console.Write(myDllManager.Invoke("你的DLL文件名.dll","命名空间名称","类名","函数名",null));

// 卸载 DLL

myDllManager.UnLoadDll();

}

三、动态调用DLL的类文件如下:

//添加引用

using System.IO;

using System.Reflection;

public class DllManager

{

private static Assembly MyAssembly;// 记录要导入的程序集

/// <summary>

/// 调用指定DLL中的指定类的指定函数

/// </summary>

/// <param name="lpFileName">DLL文件名或者路径</param>

/// <param name="Namespace">DLL中的命名空间</param>

/// <param name="ClassName">中的命名空间中的类</param>

/// <param name="lpProcName">类中的方法</param>

/// <param name="ObjArray_Parameter">方法参数</param>

/// <returns></returns>

public object Invoke(string lpFileName, string Namespace, string ClassName, string lpProcName, object[] ObjArray_Parameter)

{

try

{// 判断 MyAssembly 是否为空或 MyAssembly 的命名空间不等于要调用方法的命名空间,如果条件为真,就用 Assembly.Load 加载所需 DLL 作为程序集

if (MyAssembly == null || MyAssembly.GetName().Name != Namespace)

MyAssembly = Assembly.Load(LoadDll(lpFileName));

Type[] type = MyAssembly.GetTypes();

foreach (Type t in type)

{

if (t.Namespace == Namespace && t.Name == ClassName)

{

MethodInfo m = t.GetMethod(lpProcName);

if (m != null)

{// 调用并返回

object o = Activator.CreateInstance(t);

return m.Invoke(o, ObjArray_Parameter);

}

else

System.Windows.Forms.MessageBox.Show(" 装载出错 !");

}

}

}

catch (System.NullReferenceException e)

{

System.Windows.Forms.MessageBox.Show(e.Message);

}

return (object)0;

}

/// <summary>

/// 加载DLL文件

/// </summary>

/// <param name="lpFileName">DLL文件名或者路径</param>

/// <returns></returns>

private byte[] LoadDll(string lpFileName)

{

Assembly NowAssembly = Assembly.GetEntryAssembly();

Stream fs = null;

try

{// 尝试读取资源中的 DLL

fs = NowAssembly.GetManifestResourceStream(NowAssembly.GetName().Name + "." + lpFileName);

}

finally

{// 如果资源没有所需的 DLL ,就查看硬盘上有没有,有的话就读取

if (fs == null && !File.Exists(lpFileName)) throw (new Exception(" 找不到文件 :" + lpFileName));

else if (fs == null && File.Exists(lpFileName))

{

FileStream Fs = new FileStream(lpFileName, FileMode.Open);

fs = (Stream)Fs;

}

}

byte[] buffer = new byte[(int)fs.Length];

fs.Read(buffer, 0, buffer.Length);

fs.Close();

return buffer; // 以 byte[] 返回读到的 DLL

}

public void UnLoadDll()

{

// 使 MyAssembly 指空

MyAssembly = null;

}

}

//上述代码是网站搜集的。已经测试过自己的数据库操作DLL文件。没有问题,希望能方便到大家。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: