Python ctypes:初始化 c_char_p()
我写了一个简单的 C++ 程序来说明我的问题:
extern "C"{
int test(int, char*);
}
int test(int i, char* var){
if (i == 1){
strcpy(var,"hi");
}
return 1;
}
我将其编译成一个 so.c++ 程序。我从 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
我缺少什么?
谢谢。
I wrote a simple C++ program to illustrate my problem:
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:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用字符
"bye"
初始化的字符串,以及您不断获取并分配给charP
的地址,在第一次之后不会重新初始化。请遵循此处的建议:
“指向可变内存的指针”正是您的 C 函数所期望的,因此您应该使用 create_string_buffer 函数来创建该缓冲区,如文档所解释的那样。
The string which you initialized with the characters
"bye"
, and whose address you keep taking and assigning tocharP
, does not get re-initialized after the first time.Follow the advice here:
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.我猜测 python 正在为所有 5 次传递重用相同的缓冲区。一旦你将它设置为“hi”,你就永远不会将它设置回“bye”你可以做这样的事情:
但要小心,
strcpy
只是要求缓冲区溢出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:
but be careful,
strcpy
is just asking for a buffer overflow