常用的Dllimport方式
暂时省略
使用Api进行加载
工具类:
public class DLLWrapper
{
///<summary>
/// API LoadLibrary
///</summary>
[DllImport("Kernel32")]
public static extern Int64 LoadLibrary(string funcname);
///<summary>
/// API GetProcAddress
///</summary>
[DllImport("Kernel32")]
public static extern Int64 GetProcAddress(Int64 handle, string funcname);
///<summary>
/// API FreeLibrary
///</summary>
[DllImport("Kernel32")]
public static extern Int64 FreeLibrary(Int64 handle);
///<summary>
///通过非托管函数名转换为对应的委托, by jingzhongrong
///</summary>
///<param name="dllModule">Get DLL handle by LoadLibrary</param>
///<param name="functionName">Unmanaged function name</param>
///<param name="t">ManageR type对应的委托类型</param>
///<returns>委托实例,可强制转换为适当的委托类型</returns>
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);
}
///<summary>
///将表示函数地址的IntPtr实例转换成对应的委托
///</summary>
public static Delegate GetDelegateFromIntPtr(IntPtr address, Type t)
{
if (address == IntPtr.Zero)
return null;
else
return Marshal.GetDelegateForFunctionPointer(address, t);
}
///<summary>
///将表示函数地址的int转换成对应的委托
///</summary>
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也可以正常使用?
2022/09/05 经过一端时间的了解 windows操作系统,真实内存大小与应用程序无关,应用程序寻址采用VA。此问题过于小白,关闭。