c++ - Python ctypes : initializing c_char_p()

标签 c++ python ctypes shared-objects

我写了一个简单的 C++ 程序来说明我的问题:

extern "C"{
    int test(int, char*);
}

int test(int i, char* var){
    if (i == 1){
        strcpy(var,"hi");
    }
    return 1;
}

我把它编译成一个 so.从 python 我调用:

from ctypes import *

libso = CDLL("Debug/libctypesTest.so")
func = libso.test
func.res_type = c_int

for i in xrange(5):
    charP = c_char_p('bye')
    func(i,charP)
    print charP.value

当我运行它时,我的输出是:

bye
hi
hi
hi
hi

我预计:

bye
hi
bye
bye
bye

我错过了什么?

谢谢。

最佳答案

您使用字符 "bye" 初始化的字符串,以及您一直获取并分配给 charP 的地址,在第一次后不会重新初始化.

听从建议here :

You should be careful, however, not to pass them to functions expecting pointers to mutable memory. If you need mutable memory blocks, ctypes has a create_string_buffer function which creates these in various ways.

“指向可变内存的指针”正是您的 C 函数所期望的,因此您应该使用 create_string_buffer 函数来创建该缓冲区,如文档所述。

关于c++ - Python ctypes : initializing c_char_p(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1871375/

相关文章:

java - 作为 Java 开发人员,C 还是 C++?

c++ - OpenCV calibrateCamera() 断言失败

c++ - 函数返回指向类的指针时是否调用复制构造函数?

python - 线程.定时器类型错误: an integer is required

python: ctypes,在 python 中读取 POINTER(c_char)

c++ - SDL2 中的灰度图像

python sprereboot命令不起作用

python - 找不到 Microsoft Visual FoxPro 支持库

python - 从 Python 调用 Rust 时出错

c++ - 从 Python 调用定制的 C++ dll