[原]C# 跨平台调用C++的函数指针

    此文主要讲一下列子,通过列子就能很清楚的看到是如何用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;
    }


原文地址:https://www.cnblogs.com/wubiyu/p/1287632.html