获取IntPtr指向的数组大小

时间:2014-01-03 21:53:49

标签: c# pinvoke intptr

我有一个本机C ++函数,我使用pinvoke从C#项目调用。

extern "C" _declspec(dllexport) void GetCmdKeyword( wchar_t** cmdKeyword, uint  pCmdNum )
{
 int status = 1;
 int       count     = 0;
 int       i         = 0;

 if( cmdKeyword == NULL )
      return ERR_NULL_POINTER;

 //search command in command list by letter from 'A' to 'Z'
 count = sizeof( stCommandList ) / sizeof( COMMANDLIST ) ;

 for ( i = 0 ; i < count && status != 0; i++ )
 {
      if ( pCmdNum != stCommandList[i].ulCommand )
           continue;
      *cmdKeyword = &stCommandList[i].CommandKeyWord[0];
      status = 0 ;
 }

}

其中stCommandList是COMMANDLIST类型的结构,CommandKeyWord成员是char数组。

要从C#调用此函数,我需要传递什么参数? cmdKeyword应填充在char数组或C#端的字符串中,即我需要复制ptr指向C#文件中的int数组的位置的内容。如果我知道长度,我可以使用Marshal.Copy来做同样的事情。我现在该怎么办?另外,我不想使用不安全的。 Globalsize对此有帮助吗?

1 个答案:

答案 0 :(得分:1)

您无法从指针推断出长度。必须将信息作为单独的值与指向数组的指针一起传递。

我想知道你为什么使用原始IntPtr而不是C#数组。我认为您在之前的问题中接受的答案包含您需要的代码:Pinvoking a native function with array arguments


好的,看看问题的编辑,实际情况有点不同。该函数返回一个指向以null结尾的宽字符数组的指针。你的pinvoke应该是:

[DllImport(...)]
static extern void GetCmdKeyword(out IntPtr cmdKeyword, uint pCmdNum);

这样称呼:

IntPtr ptr;
GetCmdKeyword(ptr, cmdNum);
string cmdKeyword = Marshal.PtrToStringUni(ptr);
相关问题