Python ctypes:初始化 c_char_p()

发布于 2024-08-14 22:02:38 字数 597 浏览 3 评论 0原文

我写了一个简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

顾挽 2024-08-21 22:02:38

您使用字符 "bye" 初始化的字符串,以及您不断获取并分配给 charP 的地址,在第一次之后不会重新初始化。

请遵循此处的建议:

但是,您应该小心,不要
将它们传递给期望的函数
指向可变内存的指针。如果你
需要可变内存块,ctypes 有
create_string_buffer 函数
以各种方式创建这些。

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

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.

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.

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.

一梦等七年七年为一梦 2024-08-21 22:02:38

我猜测 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;
}

但要小心,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:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文