gpt4 book ai didi

python - 从 C 访问 PyBuffer 的内容

转载 作者:太空宇宙 更新时间:2023-11-04 01:43:44 35 4
gpt4 key购买 nike

我在 python 中创建了一个缓冲区对象,如下所示:

f = io.open('some_file', 'rb')
byte_stream = buffer(f.read(4096))

我现在通过 SWIG 将 byte_stream 作为参数传递给 C 函数。我有一个用于转换数据的类型映射,如下所示:

%typemap(in) unsigned char * byte_stream {
PyObject *buf = $input;
//some code to read the contents of buf
}

我已经尝试了几种不同的方法,但错误无法获取我的 byte_stream 的实际内容/值。如何使用 C API 转换或访问我的 byte_stream 的内容?有许多不同的方法可以将 C 数据转换为缓冲区,但我找不到相反的方法。我试过在 gcb 中查看这个对象,但它和它指向的包含我的数据的值都没有。

(我使用缓冲区是因为我想避免在从文件中读取数据时将数据转换为字符串的开销)我在 Linux 上使用 python 2.6。

--谢谢帕维尔

最佳答案

I'm using buffers because I want to avoid the overhead of converting the data to a string when reading it from the file

你没有回避任何事情。该字符串已由 read() 方法构建。调用 buffer() 只是构建一个指向该字符串的附加缓冲区对象。

至于获取缓冲区对象指向的内存,请尝试 PyObject_AsReadBuffer()。另见 http://docs.python.org/c-api/objbuffer.html .

关于python - 从 C 访问 PyBuffer 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2128195/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com