C# 如何跨平台调用C++的函数指针!
函數指針搞C++的人應該都知道,效率高,易用性強,隱蔽代碼等。在C++里面調用C++寫的dll的函數指針那是在容易不過了。使用C#就稍微麻煩點了!那怎么掉呢?通過上面的第一篇文章我們知道應該使用委托 delegate。如果再高級點,定義一個函數指針結構(有點像linux的內核),也同樣可以用C#調用。
提示:委托就和C++中的函數指針一樣
借用一下別人的列子:在C++的一個標準Win32 api 庫ccLic.dll中有一個函數void* WINAPI GetFunctionAddress(unsigned int sn);此函數通過傳sn序號得到函數指針即一個函數的地址.之后再通過返回回來的地址進行其它函數的調用
?? ?那么我們必須知道.一個sn號對應的函數結構如?sn=1 ->?bool WINAPI CCAskServerLicenseInfo(const char* server_address,unsigned short port,PCcLic_Info plicenseinfo)
在其中?
typedef struct _CcLic_Info {
char?ower[64];
unsigned short manage_ip;
unsigned short ramained_ip;
unsigned short useable_time;
unsigned char type;
} CcLic_Info,*PCcLic_Info;
此列的目的就是通過C#調用?CCAskServerLicenseInfo 函數.
?
????????[DllImport(
????????public?static?extern?System.IntPtr?Matrix(System.UInt32?sn);//聲名入口函數
??????? //定義函數指針模型
????????public?delegate?System.Int32?CCAskServerLicenseInfoHandle(System.String?servername,?System.UInt16?port,?System.IntPtr?ptr);
????????public?static?LicenseInfo?GetLicentInfo(String?server,?System.UInt16?port)
????????{
?? ? ? ? ? ?System.IntPtr?fPtr?=?Matrix(1);//獲得CCAskServerLicenseInfo地址?? ? ? ? ? CCAskServerLicenseInfoHandle?CCAskServerLicenseInfo?=?Marshal.GetDelegateForFunctionPointer(fPtr,?typeof(CCAskServerLicenseInfoHandle))?as?CCAskServerLicenseInfoHandle;//將地址轉換為C#中的函數指針
????????????LicenseInfo?info?=?new?LicenseInfo();//聲名結構并初始化
????????????IntPtr?infoPtr?=?Marshal.AllocCoTaskMem(Marshal.SizeOf(info));//將結構體轉換為指針
????????????CCAskServerLicenseInfo(server,?port,?infoPtr);//調用函數
????????????info?=?(LicenseInfo)Marshal.PtrToStructure(infoPtr,?typeof(LicenseInfo));//將指針轉換為結構體
????????????return?info;
????????}
?[StructLayout(LayoutKind.Sequential,?CharSet?=?CharSet.Ansi)]
????public?struct?LicenseInfo
????{
????????[MarshalAs(UnmanagedType.ByValArray,?SizeConst?=?64)]
????????public?System.Char[]?ower;
????????public?System.UInt16?manage_ip;?
????????public?System.UInt16?ramained_ip;
????????public?System.UInt16?useable_time;?
????????public?System.Byte?type;
????}
正好項目有個Mobile需要調用,需要用此方式,我試試看行不行.
轉載于:https://www.cnblogs.com/qhonge/archive/2008/10/06/1304461.html
總結
以上是生活随笔為你收集整理的C# 如何跨平台调用C++的函数指针!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阴影及定位
- 下一篇: c# char unsigned_dll