c++ - 如何从 C++ 返回 char ** 并使用 ctypes 将其填充到 Python 列表中?

标签 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

以下是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

在 python 中输出是整数:?

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

19306416

最佳答案

ctypes doc说:“默认情况下,假定函数返回 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)

关于c++ - 如何从 C++ 返回 char ** 并使用 ctypes 将其填充到 Python 列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15709994/

相关文章:

c++ - C++ 中的析构函数和继承?

c++ - OpenCV: "Feature Matching with FLANN"教程 - 获取异常

c++ - QT 中的 moc 不会编译我的 c++ 头文件。说它太不同了

python - 安装了 python 3 和 pip 3 但 pip -V 显示 19.2.3

python - 如何从python中的列表字典中添加元素

python - 使用Ctypes在Python程序中调用call by reference c程序

python - 功能无法正常工作

C++ lambdas, "error: expected expression"

python - 来自元组的稀疏数组

python - 使用 ctypes 通过引用传递整数数组