Python ctypes:初始化 c_char_p()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1871375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:14:39  来源:igfitidea点击:

Python ctypes: initializing c_char_p()

c++pythonctypesshared-objects

提问by Mark

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:

我把它编译成一个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

When I run this, my output is:

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

bye
hi
hi
hi
hi

I expected:

我期望:

bye
hi
bye
bye
bye

What am I missing?

我错过了什么?

Thanks.

谢谢。

回答by Alex Martelli

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_bufferfunction to create that buffer, as the docs explain.

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

回答by Evan Teran

I am guessing python is reusing the same buffer for all 5 passes. once you set it to "hi", you never set it back to "bye" You can do something like this:

我猜 python 正在为所有 5 次通过重用相同的缓冲区。一旦你将它设置为“hi”,你就永远不会将它设置回“bye”你可以做这样的事情:

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, strcpyis just asking for a buffer overflow

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