简体   繁体   English

Python ctypes:初始化c_char_p()

[英]Python ctypes: initializing c_char_p()

I wrote a simple C++ program to illustrate my problem: 我写了一个简单的C ++程序来说明我的问题:

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

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

I compile this into an so. 我把它编译成一个。 From python I call: 从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

When I run this, my output is: 当我运行它时,我的输出是:

bye
hi
hi
hi
hi

I expected: 我期望:

bye
hi
bye
bye
bye

What am I missing? 我错过了什么?

Thanks. 谢谢。

The string which you initialized with the characters "bye" , and whose address you keep taking and assigning to charP , does not get re-initialized after the first time. 您使用字符"bye"初始化的字符串,以及您继续使用并分配给charP的地址,在第一次之后不会重新初始化。

Follow the advice 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. 如果你需要可变内存块,ctypes有一个create_string_buffer函数,它以各种方式创建它们。

A "pointer to mutable memory" is exactly what your C function expects, and so you should use the create_string_buffer function to create that buffer, as the docs explain. “指向可变内存的指针”正是您的C函数所期望的,因此您应该使用create_string_buffer函数来创建该缓冲区,正如文档所解释的那样。

I am guessing python is reusing the same buffer for all 5 passes. 我猜python正在为所有5次传递重用相同的缓冲区。 once you set it to "hi", you never set it back to "bye" You can do something like this: 一旦你把它设置为“hi”,你就不会把它设置回“再见”你可以这样做:

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

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

but be careful, strcpy is just asking for a buffer overflow 但要小心, strcpy只是要求缓冲区溢出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM