Pythonctypes.string_在,指针正确,但结果字符串n

2024-04-28 18:30:29 发布

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

我正在用下面的例子学习如何使用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


Tags: 文件代码srclenctypespoststruct例子
3条回答

也许你应该用c_char_p代替c_u void

因为Python GC吃了create_string_buffer(s),但是src!在

改成这样就可以了:

buf = create_string_buffer(s)
foolib.foo(byref(o), buf)

create_string_buffer(s)生成一个临时字符串,该字符串在函数调用后被垃圾回收。只需传递实际字符串,因为您没有修改它:

s = "iooxooiddfggggggggggggvd"
foolib.foo(byref(o), s)

更改前的输出(第二个字符串中的垃圾表示访问垃圾收集的内存,因此行为未定义):

^{pr2}$

变更后输出:

21
xooiddfggggggggggggvd
iooxooiddfggggggggggggvd

相关问题 更多 >