代码如下:
[DllImport("Kernel32")]
public static extern int LoadLibrary(String funcname); [DllImport("Kernel32")]
public static extern int GetProcAddress(int handle, String funcname); [DllImport("Kernel32")]
public static extern bool FreeLibrary(int handle); public static Delegate GetFunctionAddress(int dllModule, string functionName, Type t)
{
int address = GetProcAddress(dllModule, functionName);
if (address == 0)
return null;
else
return (Delegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);
} public delegate bool Start(); private void btnScua_Click(object sender, EventArgs e)
{
int hModule = 0; hModule = Program.LoadLibrary("scua.dll");
if (hModule == 0)
{
MessageBox.Show("找不到DLL!");
return;
}
Start dllFun = (Start)Program.GetFunctionAddress(hModule, "Start", typeof(Start));
if (dllFun == null)
{
MessageBox.Show("DLL出错!");
return;
}
try
{
dllFun();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
}
异常如下:
------------------------------------------------------
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at BoardLoad.Form1.Start.Invoke()
[DllImport("Kernel32")]
public static extern int LoadLibrary(String funcname); [DllImport("Kernel32")]
public static extern int GetProcAddress(int handle, String funcname); [DllImport("Kernel32")]
public static extern bool FreeLibrary(int handle); public static Delegate GetFunctionAddress(int dllModule, string functionName, Type t)
{
int address = GetProcAddress(dllModule, functionName);
if (address == 0)
return null;
else
return (Delegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);
} public delegate bool Start(); private void btnScua_Click(object sender, EventArgs e)
{
int hModule = 0; hModule = Program.LoadLibrary("scua.dll");
if (hModule == 0)
{
MessageBox.Show("找不到DLL!");
return;
}
Start dllFun = (Start)Program.GetFunctionAddress(hModule, "Start", typeof(Start));
if (dllFun == null)
{
MessageBox.Show("DLL出错!");
return;
}
try
{
dllFun();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
}
异常如下:
------------------------------------------------------
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at BoardLoad.Form1.Start.Invoke()
int handle这里应使用IntPtr类型