Main Code of the called TestDll. dll file:
Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace TestDll
{
Public class TestDll
{
Public string HandleStr (string str)
{
Return "[" + str + "]";
}
}
}
Code for calling the HandleStr method of TestDll. dll:
Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Text;
Using System. Windows. Forms;
Using System. Reflection;
Namespace DynamicInvokeDll
{
Public partial class FrmMain: Form
{
Public FrmMain ()
{
InitializeComponent ();
}
Private void FrmMain_Load (object sender, EventArgs e)
{
Object [] obj = new object [1];
Obj [0] = "DllInvoke ";
Object o2 = DllInvoke ("TestDll. dll", "TestDll", "TestDll", "HandleStr", obj );
MessageBox. Show (o2.ToString ());
}
/// <Summary>
/// Call DLL dynamically
/// </Summary>
/// <Param name = "DllFileName"> dll name </param>
/// <Param name = "NameSpace"> NameSpace </param>
/// <Param name = "ClassName"> class name </param>
/// <Param name = "MethodName"> method name </param>
/// <Param name = "ObjArrayParams"> parameter array </param>
/// <Returns> </returns>
Private object DllInvoke (string DllFileName, string NameSpace, string ClassName, string MethodName, object [] ObjArrayParams)
{
Try
{
// Load the Assembly
Assembly DllAssembly = Assembly. LoadFrom (DllFileName );
Type [] DllTypes = DllAssembly. GetTypes ();
Foreach (Type DllType in DllTypes)
{
// Find the namespace and class to call
If (DllType. Namespace = NameSpace & DllType. Name = ClassName)
{
// Locate and call the method to be called
MethodInfo MyMethod = DllType. GetMethod (MethodName );
If (MyMethod! = Null)
{
Object mObject = Activator. CreateInstance (DllType );
Return MyMethod. Invoke (mObject, ObjArrayParams );
}
}
}
}
Catch (Exception mEx)
{
}
Return (object) 0;
}
}
}