常用的Dllimport方式
暂时省略
使用Api进行加载
工具类:
public class DLLWrapper
{
[DllImport("Kernel32")]
public static extern Int64 LoadLibrary(string funcname);
[DllImport("Kernel32")]
public static extern Int64 GetProcAddress(Int64 handle, string funcname);
[DllImport("Kernel32")]
public static extern Int64 FreeLibrary(Int64 handle);
public static Delegate GetFunctionAddress(Int64 dllModule, string functionName, Type t)
{
Int64 address = GetProcAddress(dllModule, functionName);
if (address == 0)
return null;
else
return Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);
}
public static Delegate GetDelegateFromIntPtr(IntPtr address, Type t)
{
if (address == IntPtr.Zero)
return null;
else
return Marshal.GetDelegateForFunctionPointer(address, t);
}
public static Delegate GetDelegateFromIntPtr(int address, Type t)
{
if (address == 0)
return null;
else
return Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);
}
}
notice: 作者加载的是64程序集,所有handle采用int64进行接收。如果32程序集,可使用int(int32) 但64位必须使用(int64),使用int32 进行内存寻址默认高32位全部补0寻址错误。
函数调用
class Program
{
static void Main(string[] args)
{
string dllpath = "NetCom.dll";
Console.WriteLine(dllpath);
Int64 handle = hModule(dllpath);
bool b =ConnectToModel(handle, "224.0.0.0",4196, "./MMI1");
Console.WriteLine(b.ToString()+handle);
DLLWrapper.FreeLibrary(handle);
Console.ReadKey();
}
private static Int64 hModule(string dllpath)
{
Int64 _hModule = DLLWrapper.LoadLibrary(dllpath);
if (_hModule == 0)
{
return 0;
}
return _hModule;
}
delegate bool _connectToModel(string ip,int port,string dir);
private static bool ConnectToModel(Int64 handle,string ip, int port, string dir)
{
try
{
_connectToModel connect = (_connectToModel) DLLWrapper.GetFunctionAddress(handle, "ConnectToModel", typeof(_connectToModel));
return connect(ip,port,dir);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
疑问请各位指教
在64位操作系统中,内存为4g大小,是否采用int32也可以正常使用?
|