我已经在 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 have created a buffer object in python like so:
f = io.open('some_file', 'rb')
byte_stream = buffer(f.read(4096))
I'm now passing byte_stream
as a parameter to a C function, through SWIG. I have a typemap for converting the data which looks like this:
%typemap(in) unsigned char * byte_stream {
PyObject *buf = $input;
//some code to read the contents of buf
}
I have tried a few different things bug can't get to the actual content/value of my byte_stream. How do I convert or access the content of my byte_stream
using the C API? There are many different methods for converting a C data to a buffer but none that I can find for going the other way around.
I have tried looking at this object in gcb but neither it, or the values it points to contain my data.
(I'm using buffers because I want to avoid the overhead of converting the data to a string when reading it from the file)
I'm using python 2.6 on Linux.
--
Thanks Pavel
发布评论
评论(2)
您没有避免任何事情。该字符串已由
read()
方法构建。调用 buffer() 只是构建一个指向该字符串的附加缓冲区对象。至于获取缓冲区对象指向的内存,请尝试
PyObject_AsReadBuffer()
。另请参阅 http://docs.python.org/c-api/objbuffer.html< /a>.You are not avoiding anything. The string is already built by the
read()
method. Callingbuffer()
just builds an additional buffer object pointing to that string.As for getting at the memory pointed to by the buffer object, try
PyObject_AsReadBuffer()
. See also http://docs.python.org/c-api/objbuffer.html.一旦您对文件对象使用
read
方法,数据就会转换为str
对象;调用 buffer 方法不会将其转换为任何类型的流。如果您想避免创建字符串对象的开销,您可以简单地将文件对象传递给 C 代码,然后通过 其 C API。As soon as you use the
read
method on your file object, the data will be converted to astr
object; calling thebuffer
method does not convert it into a stream of any kind. If you want to avoid the overhead of creating the string object, you could simply pass the file object to your C code and then use it via its C API.