在 C# 中将 IntPtr 转换为 char**
Convert IntPtr to char** in C#
我想解释以下非托管函数的输出:
afc_error_t afc_get_device_info (afc_client_t client, char ***device_information)
我用代码导入dll:
[DllImport("libimobiledevice.dll", CallingConvention = CallingConvention.Cdecl)]
internal static extern short afc_get_device_info(IntPtr client, out IntPtr info);
只要我只需要将响应转换为字符串 Marshal.PtrToStringAnsi
就可以了。但是我不知道如何将该 IntPtr 转换回 char 数组。
应该是这样的:
IntPtr di;
int result = afc_read_directory(client, @"C:\", out di);
if (di == IntPtr.Zero)
{
throw new Exception();
}
IntPtr di2 = di;
while (true)
{
IntPtr ptr = Marshal.ReadIntPtr(di2);
if (ptr == IntPtr.Zero)
{
break;
}
string str = Marshal.PtrToStringAnsi(ptr);
if (str == string.Empty)
{
break;
}
di2 = di2 + IntPtr.Size;
}
尝试一下是否有效,然后我会解释如何...
重要 你在这里泄漏内存...
我在 C:
中找到了这个例子
char **dirs = NULL;
afc_read_directory(afc, "/eafaedf", &dirs);
if (!dirs)
afc_read_directory(afc, "/", &dirs);
printf("Directory time.\n");
for (i = 0; dirs[i]; i++) {
printf("/%s\n", dirs[i]);
free(dirs[i]);
}
if (dirs)
free(dirs);
你负责释放内存(看循环里面的free
和最后的free?)。在这种情况下(以及对于 return C 字符串数组的其他方法,您可以使用 afc_dictionary_free
。请注意,其他方法如 afc_receive_data
是 return 单个内存块无法使用。
我想解释以下非托管函数的输出:
afc_error_t afc_get_device_info (afc_client_t client, char ***device_information)
我用代码导入dll:
[DllImport("libimobiledevice.dll", CallingConvention = CallingConvention.Cdecl)]
internal static extern short afc_get_device_info(IntPtr client, out IntPtr info);
只要我只需要将响应转换为字符串 Marshal.PtrToStringAnsi
就可以了。但是我不知道如何将该 IntPtr 转换回 char 数组。
应该是这样的:
IntPtr di;
int result = afc_read_directory(client, @"C:\", out di);
if (di == IntPtr.Zero)
{
throw new Exception();
}
IntPtr di2 = di;
while (true)
{
IntPtr ptr = Marshal.ReadIntPtr(di2);
if (ptr == IntPtr.Zero)
{
break;
}
string str = Marshal.PtrToStringAnsi(ptr);
if (str == string.Empty)
{
break;
}
di2 = di2 + IntPtr.Size;
}
尝试一下是否有效,然后我会解释如何...
重要 你在这里泄漏内存...
我在 C:
中找到了这个例子char **dirs = NULL;
afc_read_directory(afc, "/eafaedf", &dirs);
if (!dirs)
afc_read_directory(afc, "/", &dirs);
printf("Directory time.\n");
for (i = 0; dirs[i]; i++) {
printf("/%s\n", dirs[i]);
free(dirs[i]);
}
if (dirs)
free(dirs);
你负责释放内存(看循环里面的free
和最后的free?)。在这种情况下(以及对于 return C 字符串数组的其他方法,您可以使用 afc_dictionary_free
。请注意,其他方法如 afc_receive_data
是 return 单个内存块无法使用。