【问题标题】:char** callback from c++ to C# and send data backchar** 从 c++ 回调到 C# 并发送回数据
【发布时间】:2013-10-28 08:43:27
【问题描述】:

我有一个问题,我希望你们能帮助我解决这个问题。我对 C# 编程比较陌生,从未使用过 c++,所以我无法弄清楚以下问题:

我正在使用 SDK(用 c++ 编写)从特定类型的设备接收和请求 DDNS 更新。设置回调起作用,并且在预期时间触发回调。

文档说回调包含一个 char** 参数,但我不知道该怎么做。我尝试了很多选项,应用程序不会崩溃的唯一方法是使用 IntPtr 作为该参数。但是当我这样做时,我无法为该 IntPtr 设置值。

我使用回调找到的原始代码:

int CALLBACK CBGetDeviceAddr(int *pResult, char** pIPAddr,unsigned short *pSdkPort, char *szDeviceID, char*szDeviceName)   
{   
int nCount=g_pDeviceList->GetItemCount();   
memset(g_szIPAddr, 0, MAX_IP_LEN+1);   
*pIPAddr=g_szIPAddr;   

BOOL bRet=FALSE;   
for(int i = 0; i< nCount; i++)   
{   

    if (strcmp(szDeviceID,(LPCTSTR)g_pDeviceList->GetItemText(i, 2).GetBuffer(0)) == 0)//,g_pDeviceList->GetItemText(i,2).GetLength()   
    {   
        *pResult=1;   
        strcpy(*pIPAddr,g_pDeviceList->GetItemText(i,0).GetBuffer(0));   
        *pSdkPort = atoi(g_pDeviceList->GetItemText(i,4).GetBuffer(0));   
        TRACE("CALLBACK CBGetDeviceAddrInfo:in DeviceID=%s, DeviceName=%s,out DeviceIP=%s,DevicePort = %d\n",\   
            szDeviceID, szDeviceName, *pIPAddr, *pSdkPort);   
        bRet = TRUE;   
        break;   
    }   
}   

if (!bRet)   
{   
    *pResult=0;   
    *pIPAddr=NULL;   
    TRACE("CALLBACK CBGetDeviceAddrInfo:in DeviceID=%s, DeviceName=%s,out no such device online!!!\n",\   
        szDeviceID, szDeviceName);   
}   

return 0;   
}

我目前正在使用的:

private int CBF_GetADeviceIP(ref int pResult, ref IntPtr pIPAddr, ref ushort pSdkPort, string szDeviceID, string szDeviceName)

这适用于 pResult 和 pSdkPort(所以我可以发回数据),但不能用 pIPAddr 做任何事情。

有什么帮助吗? 谢谢

【问题讨论】:

    标签: c# c++ marshalling intptr


    【解决方案1】:

    通常当你看到char**时,它的意思是“这个参数将用于返回一个字符串”。

    在为此类参数编写 P/Invoke 时,通常可以使用ref string(如果字符串是输入,或输入和输出)或out string(如果字符串只是输出)。

    您需要知道的另一件事是本机方法是否需要 ANSI 或 Unicode 字符串。

    要指定使用哪种字符串编码,请使用CharSet 属性参数:

    [DllImport("MyDLL.dll", CharSet = CharSet.Unicode)]
    

    [DllImport("MyDLL.dll", CharSet = CharSet.Ansi)]
    

    等等。

    【讨论】:

    • 感谢您的快速回复。问题是我使用 ref 而不是 out。所以谢谢!!
    【解决方案2】:

    我不太会 C#,但 pIPAddr 不是指向字符串的指针吗?

    所以你应该将该参数声明为ref string pIPAddr

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      相关资源
      最近更新 更多