如何从C++返回char**并使用ctypes将其填入Python的列表中?

Sho*_*uri 1 c++ python ctypes

我一直在尝试从C++返回一个字符串数组到python a:

// c++ code
extern "C" char** queryTree(char* treename, float rad, int kn, char*name, char *hash){
    //.... bunch of other manipulation using parameters...

    int nbr = 3; // number of string I wish to pass
    char **queryResult = (char **) malloc(nbr* sizeof(char**));
    for (int j=0;j<nbr;j++){
        queryResult[j] = (char *) malloc(strlen(results[j]->id)+1);
        if(queryResult[j]){
            strcpy(queryResult[j], "Hello"); // just a sample string "Hello"
        } 
    }
    return queryResult;
}
// output in C++:
Hello
Hello
Hello
Run Code Online (Sandbox Code Playgroud)

以下是python中的代码:

libtest = ctypes.c_char_p * 3;
libtest = ctypes.CDLL('./imget.so').queryTree("trytreenew64", ctypes.c_float(16), ctypes.c_int(20), ctypes.c_char_p(filename), ctypes.c_char_p(hashval))
print libtest
Run Code Online (Sandbox Code Playgroud)

python中的输出是整数:?

我是python的新手.我知道我在python方面做错了什么.我一直在寻找其他问题,他们正在传递一个char*但是我无法让它为char**工作.我试了几个小时.任何帮助,将不胜感激.

19306416
Run Code Online (Sandbox Code Playgroud)

tde*_*ney 6

ctypes的文档说:"默认情况下,假定函数返回c的int类型的其它返回类型可以通过设置函数对象的restype属性."

这应该工作:

(编辑添加POINTER)

imget = ctypes.CDLL('./imget.so')
imget.queryTree.restype = ctypes.POINTER(ctypes.c_char_p * 3)
imget.queryTree.argtypes = (ctypes.c_char_p, ctypes.c_float, ctypes.c_int,
    ctypes.c_char_p, ctypes.c_char_p)
libtest = imget.queryTree("trytreenew64",16, 20, filename, hashval)
Run Code Online (Sandbox Code Playgroud)