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

在使用ctypes的python中,在dll中调用函数时,如何传递char**?,python,dll,ctypes,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_si

我在用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内部崩溃。

c\u char\u p
是一个
char*
并且
argtypes
应该被分配一个元组或ctypes类型列表。使用
get_name.argtypes=(指针(c_char_p))
free\u name.argtypes=(c\u char\u p,)
。将其作为
get\u name(byref(name\u from\u dll))
传递,并将其作为
free\u name(name\u from\u dll)
释放。谢谢@eryksun,这确实有效。请发布完整答案,我会批准。
c\u char\u p
char*
并且
argtypes
应该分配一个元组或ctypes类型列表。使用
get_name.argtypes=(指针(c_char_p))
free\u name.argtypes=(c\u char\u p,)
。将其作为
get\u name(byref(name\u from\u dll))
传递,并将其作为
free\u name(name\u from\u dll)
释放。谢谢@eryksun,这确实有效。请发布完整答案,我会批准。