0

实际上我在 C# 中使用了一个 C++ dll,如下所示

我的 C++ 代码

extern "C" __declspec(dllexport)
    char**  __stdcall hh()
{
 static char* myArray[3] = {"A1", "BB2", "CC3",};
    return myArray;
}

我的 C# 代码

[DllImport(@"ourdll.dll",CharSet = CharSet.Ansi,CallingConvention = CallingConvention.StdCall)]     
      public static extern IntPtr hh();
       static void Main(string[] args)
        {
            IntPtr a = hh();
            int j = 0;
            string[] s=new string[100]; //I want this to be dynamic
           do
           {
               s[j] = Marshal.PtrToStringAnsi(Marshal.ReadIntPtr(a,4*j));
               j++;
           }
           while(s[j-1] != null);
        }

我无法获得 hh() 返回的数组的大小;如何获得数组的大小,以便我的代码行

字符串[] s=新字符串[100];更改为 string[] s=new string[ACtual Length of array];

4

2 回答 2

3

您要么必须返回数组的大小(可能是引用变量),要么可以将 NULL 终止符添加到列表中。如果使用 NULL 终止符,则可以循环遍历数组,直到找到 NULL 以确定大小。

于 2012-04-11T05:16:47.767 回答
1

如果你想在 PInvoke 中找到数组的长度,你可以使用Marshal.SizeOf(object)方法

MSDN 链接

它适用于结构

于 2012-04-11T05:34:27.680 回答