[英]from a C# method, how to call and run a DLL, where the DLL name comes from a String variable?
我是C#.NET的新手。 我正在編寫一個方法,我需要調用並運行DLL文件,其中DLL文件名來自String變量 -
String[] spl;
String DLLfile = spl[0];
如何導入此DLL並從DLL調用函數以獲取返回值? 我嘗試了以下方式..
String DLLfile = "MyDLL.dll";
[DllImport(DLLfile, CallingConvention = CallingConvention.StdCall)]
但它沒有用,因為字符串應該是'const string'類型而'const string'不支持變量。 請幫我詳細說明一下程序。 謝謝。
對於本機DLL,您可以創建以下靜態類:
internal static class NativeWinAPI
{
[DllImport("kernel32.dll")]
internal static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
internal static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetProcAddress(IntPtr hModule,
string procedureName);
}
然后使用如下:
// DLLFileName is, say, "MyLibrary.dll"
IntPtr hLibrary = NativeWinAPI.LoadLibrary(DLLFileName);
if (hLibrary != IntPtr.Zero) // DLL is loaded successfully
{
// FunctionName is, say, "MyFunctionName"
IntPtr pointerToFunction = NativeWinAPI.GetProcAddress(hLibrary, FunctionName);
if (pointerToFunction != IntPtr.Zero)
{
MyFunctionDelegate function = (MyFunctionDelegate)Marshal.GetDelegateForFunctionPointer(
pointerToFunction, typeof(MyFunctionDelegate));
function(123);
}
NativeWinAPI.FreeLibrary(hLibrary);
}
MyFunctionDelegate
是delegate
。 例如:
delegate void MyFunctionDelegate(int i);
您可以使用LoadAssembly
方法和CreateInstance
方法來調用方法
Assembly a = Assembly.Load("example");
// Get the type to use.
Type myType = a.GetType("Example");
// Get the method to call.
MethodInfo myMethod = myType.GetMethod("MethodA");
// Create an instance.
object obj = Activator.CreateInstance(myType);
// Execute the method.
myMethod.Invoke(obj, null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.