Python ctypes:初始化c_char_p()

2024-05-19 19:17:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个简单的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

我错过了什么?

谢谢。


Tags: test程序returnifsovarexternhi
2条回答

您用字符"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函数来创建缓冲区,正如文档所解释的那样。

我猜python对所有5个进程都在重用同一个缓冲区。一旦设置为“嗨”,就再也不会设置为“再见”,您可以执行以下操作:

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

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

但是要小心,strcpy只是要求缓冲区溢出

相关问题 更多 >