How to copy bytes from ctypes structure to a buffer created from create_string_buffer

I have a ctypes structure (for example):

from ctypes import * class Foo(Structure): _fields_ = [('f1',c_uint), ('f2',c_uint)] 

I would like to copy an instance of this structure into a buffer created from create_string_buffer (whose size is larger than the size needed for a single Foo instance).

Example:

 f = Foo() f.f1=1; f.f2=2; buf = create_string_buffer(100) buf[0:sizeof(f)] = f 

I know that you can read and write data to / from structures on file objects (for example, open ("bar", "rb"). Readinto (f)), so there seems to be some way to make it easy also...

+4
source share
1 answer

Avoid using an operation that creates a temporary copy, or creates temporary objects during iteration. This should be a direct copy from the source buffer to the destination buffer. The easiest way is to use ctypes.memmove :

 f = Foo() f.f1=1 f.f2=2 buf = (c_char * 100)() memmove(buf, byref(f), sizeof(f)) 

Or use a temporary array created with from_buffer (not a copy):

 memoryview(buf)[:sizeof(f)] = (c_char * sizeof(f)).from_buffer(f) 

However, the latter does not work in Python 3. It should work, but the buffer format codes used by ctypes are not supported by memoryview .

If you want the new array to be the same size or smaller, you can use the from_buffer_copy (2.6 +) array method:

 buf = (c_char * sizeof(f)).from_buffer_copy(f) 
+5
source

Source: https://habr.com/ru/post/1494546/


All Articles