【发布时间】:2018-02-25 02:58:14
【问题描述】:
在DllImport 我可以这样做:
[DllImport(".../Desktop/Calculate.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int Sub(int a, int b);
但我想决定在运行时加载哪个 dll。
所以我没有使用DllImport,但试试这个:
using System;
using System.Runtime.InteropServices;
namespace TestCall
{
class Program
{
[DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);
[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
static extern IntPtr GetProcAddress(int hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);
[DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
static extern bool FreeLibrary(int hModule);
delegate void CallMethod();
static void Main(string[] arg) //pass in string array
{
string DllName = ".../Desktop/Calculate.dll"; //would be like: string DllName = ChooseWhatDllToCall();
string FuncName = "Sub"; //would be like: string FuncName = ChooseWhatFuncToUse();
int hModule = LoadLibrary(DllName); // you can build it dynamically
if (hModule == 0) return;
IntPtr intPtr;
CallMethod action;
intPtr = GetProcAddress(hModule, FuncName);
action = (CallMethod)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(CallMethod));
action.Invoke();
}
}
}
但是我如何将Sub 定义为int Sub(int a, int b);,就像我使用DllImport 一样?
【问题讨论】:
标签: c# dll dllimport loadlibrary getprocaddress