5

私は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」は変数をサポートしていないため、機能しませんでした。詳細な手順を教えてください。ありがとう。

4

2 に答える 2

5

ネイティブ 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);
于 2012-10-10T15:34:52.167 に答える
3

メソッドを呼び出すために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);
于 2012-10-10T15:17:36.470 に答える