看看動態(tài)庫創(chuàng)建與使用相關(guān)的東西 生成與使用(托管的)dll
// file: dll.cs public class Calc { public static int Add(int a, int b) { return a + b; } }
// file: main.cs using System; class App { public static void Main() { Console.WriteLine("{0} + {1} = {2}", 123, 456, Calc.Add(123, 456)); } } 編譯: E:\> csc /target:library dll.cs E:\> csc /reference:dll.dll main.cs 運行: E:\> main 123 + 456 = 579 動態(tài)加載dllusing System; using System.Reflection; class App { public static void Main() { Assembly dll = Assembly.Load("dll"); Type calcType = dll.GetType("Calc"); object[] parameters = new object[]{123, 456}; object res = calcType.InvokeMember("Add2", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, parameters); Console.WriteLine("{0} + {1} = {2}", 123, 456, (int)res); } }
Assembly.LoadFrom("dll.dll");
Object obj = Activator.CreateInstance(calcType); object res = calcType.InvokeMember("Add", BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, parameters); 另一種寫法: MethodInfo addMethod = calcType.GetMethod("Add"); object[] parameters = new object[]{123, 456}; object obj = Activator.CreateInstance(calcType); object res = addMethod.Invoke(obj, parameters); 使用非托管 dll
// file: dll2.cpp extern "C" int __declspec(dllexport) Add(int a, int b) { return a + b; }
// file: main.cs using System; using System.Runtime.InteropServices; class App { [DllImport("dll2.dll")] public static extern int Add(int a, int b); public static void Main() { Console.WriteLine("{0} + {1} = {2}", 123, 456, Add(123, 456)); } } 編譯運行: E:\> cl dll2.cpp /LD E:\> csc main.cs E:\> main 123 + 456 = 579 這個東西被稱為Platform Invoke(P/Invoke). DllImport還有一些屬性
[DllImport("dll2.dll", EntryPoint="Add", CharSet=CharSet.Auto, CallingConvention=CallingConvention.Winapi, SetLastError=true)] 動態(tài)加載dll這又需要回到Win32 Api函數(shù)LoadLibrary、FreeLibrary這些東西了 // file: main.cs using System; using System.Runtime.InteropServices; class App { [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string dllFileName); [DllImport("kernel32.dll")] public static extern IntPtr GetProcAddress(IntPtr dllHandle, string functionName); [DllImport("kernel32.dll")] public static extern bool FreeLibrary(IntPtr dllHandle); private delegate int AddDelegate(int a, int b); public static void Main() { IntPtr handle = LoadLibrary("dll2.dll"); IntPtr pAddFunc = GetProcAddress(handle, "Add"); AddDelegate Add = (AddDelegate)Marshal.GetDelegateForFunctionPointer( pAddFunc, typeof(AddDelegate)); Console.WriteLine("{0} + {1} = {2}", 123, 456, Add(123, 456)); FreeLibrary(handle); } } 先用P/Invoke把這3個函數(shù)弄進(jìn)來,然后用它們?nèi)ヌ幚砦覀円獎討B(tài)加載的動態(tài)庫。 直接編譯 E:\> csc main.cs |
|