在python中使用ctypes,在dll中调用函数时,如何传递char **?

时间:2017-05-03 10:47:34

标签: python dll ctypes

我在用C编写的dll中有以下代码,我需要从python调用:

// get_name will allocate a char* and place it in out_name
void get_name(char** out_name)
{
    const char* the_name = "George";
    size_t the_name_size = strlen(the_name);
    *out_name = (char*)malloc(the_name_size+1);
    strncpy(*out_name, the_name, the_name_size+1);
}

// free_name will deallocate the pointer returned by get_name
void free_name(char* name_to_free)
{
    free(name_to_free);
}

在C程序中,将调用此代码:

char* name = 0;
get_name(&name);
// ... do something with name
free_name(name);

以下是我在python中尝试的内容:

from ctypes import *

the_name_lib = CDLL(path_to_dll)
the_name_lib.get_name.argtypes(POINTER(POINTER(c_char_p)))
the_name_lib.free_name.argtypes(POINTER(c_char_p))

name_from_dll = c_char_p()
name_from_dll_pointer = pointer(answer)
the_name_lib.get_name(name_from_dll_pointer)
the_name_lib.free_name(name_from_dll)

这在dll内崩溃。

0 个答案:

没有答案