简体   繁体   中英

Convert IntPtr to char** in C#

I'd like to interpret the output of the following unmanaged function:

afc_error_t afc_get_device_info (afc_client_t client, char ***device_information)

I import the dll with the code:

[DllImport("libimobiledevice.dll", CallingConvention = CallingConvention.Cdecl)]
internal static extern short afc_get_device_info(IntPtr client, out IntPtr info);

As long as I only needed to convert response to string Marshal.PtrToStringAnsi was okay. However I have no idea how to convert that IntPtr back to char array.

It should be something like:

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;
}

Try if it works, then I'll explain how...

important you are leaking memory here...

I've found this example in 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);

you are responsible for freeing the memory (see the free inside the cycle and the final free ?). In this case (and for other methods that return arrays of C-strings you can use afc_dictionary_free . Note that other methods like afc_receive_data that return a single block of memory you can't use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM