日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C# 如何跨平台调用C++的函数指针!

發布時間:2023/12/2 C# 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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(

@"ccLic.dll")]
????????
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++的函数指针!的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。