我正在用下面的例子学习如何使用ctypes,但是奇怪的问题发生了。。在
c文件在这里:
typedef struct post {
char *x;
char *y;
int x_z;
} post_t;
void
foo (post_t *o, char *src)
{
int i=0;
char *p = src;
int len = strlen(src);
for (; *p != '\0'; i++, p++) {
if (*p == 'x') {
o->x = p;
o->x_z = len-i;
}
}
o->y=src;
}
python代码在这里(测试.oy)公司名称:
^{pr2}$结构post
正在映射到pythonclass
。C文件将是一个动态库foolib.so
:
gcc-fPIC-共享-o傻瓜。所以傻瓜c
但是,奇怪的是,当我运行python test.py
时,我得到了以下输出:
21
ooiddfggggggggggggvd
ooiddfggggggggggggvd
但是string_at(o.y, len(s))
是iooxooiddfggggggggggggvd
的例外。在
我的代码哪里出错了?谢谢。在
顺便说一下,为了快速测试它,我把代码放在gist上:https://gist.github.com/hit9/7244344
也许你应该用c_char_p代替c_u void
因为Python GC吃了
create_string_buffer(s)
,但是src
!在改成这样就可以了:
create_string_buffer(s)
生成一个临时字符串,该字符串在函数调用后被垃圾回收。只需传递实际字符串,因为您没有修改它:更改前的输出(第二个字符串中的垃圾表示访问垃圾收集的内存,因此行为未定义):
^{pr2}$变更后输出:
相关问题 更多 >
编程相关推荐