• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
zd_ad
博客园    首页    新随笔    联系   管理    订阅  订阅
C# 如何跨平台调用C++的函数指针!

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 shortmanage_ip;

unsigned shortramained_ip;

unsigned shortuseable_time;

unsigned chartype;

} CcLic_Info,*PCcLic_Info;

此列的目的就是通过C#调用 CCAskServerLicenseInfo 函数.

 


+?4}4^:XAJ N$u^P0`0        [DllImport(

        //定义函数指针模型ITPUB个人空间&@.`;Lz$`M\d-o
        
public delegate System.Int32 CCAskServerLicenseInfoHandle(System.String servername, System.UInt16 port, System.IntPtr ptr);ITPUB个人空间*i?ssQ z{
ITPUB个人空间_1~\Vw$Y
        
public static LicenseInfo GetLicentInfo(String server, System.UInt16 port)ITPUB个人空间1L@2j:R-I
        {ITPUB个人空间I&KS?$J7BK7vq
            LicenseInfo info = new LicenseInfo();//声名结构并初始化
:n` qM X!\H5y;P0            IntPtr infoPtr 
= Marshal.AllocCoTaskMem(Marshal.SizeOf(info));//将结构体转换为指针
/V0ul\ OOh(F0            CCAskServerLicenseInfo(server, port, infoPtr);//调用函数ITPUB个人空间6G{Z Ww
            info 
= (LicenseInfo)Marshal.PtrToStructure(infoPtr, typeof(LicenseInfo));//将指针转换为结构体
1uG;O,Y-s0            
return info;ITPUB个人空间g3Qwo`0LG,f(v
        }ITPUB个人空间DV*gy6W{\
ITPUB个人空间 {b0K`z^Z
 [StructLayout(LayoutKind.Sequential, CharSet 
= CharSet.Ansi)]
i{$~/r1_ojl0    
public struct LicenseInfo
ve\*M$_gU#A0    {ITPUB个人空间H%E(a/h5E[
        [MarshalAs(UnmanagedType.ByValArray, SizeConst 
= 64)]ITPUB个人空间AzL4w'Q B Iy
        
public System.Char[] ower;ITPUB个人空间2v} s;W9U#U\O[K
        public System.UInt16 manage_ip; ITPUB个人空间+h`#De-hSI3F
        public System.UInt16 ramained_ip;ITPUB个人空间I jFj`+?V:r?
        public System.UInt16 useable_time; ITPUB个人空间P z0IC r%]7xV
        public System.Byte type;ITPUB个人空间wh$LP5bP%~I
    }
\}3Ya4p0

            System.IntPtr fPtr = Matrix(1);//获得CCAskServerLicenseInfo地址           CCAskServerLicenseInfoHandle CCAskServerLicenseInfo = Marshal.GetDelegateForFunctionPointer(fPtr, typeof(CCAskServerLicenseInfoHandle)) as CCAskServerLicenseInfoHandle;//将地址转换为C#中的函数指针

 

正好项目有个Mobile需要调用,需要用此方式,我试试看行不行.

@"ccLic.dll")]
2[2vja%w u:Jl&o$puIw0        
public static extern System.IntPtr Matrix(System.UInt32 sn);//声名入口函数
posted on 2010-11-04 10:55  zd_ad  阅读(447)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3