create_string_buffer()

来源:互联网 发布:淘宝售后客服工作总结 编辑:程序博客网 时间:2024/06/05 07:13

You should be careful, however, not to pass them to functions expecting pointers to mutable memory. If you need mutable memory blocks, ctypes has acreate_string_buffer() function which creates these in various ways. The current memory block contents can be accessed (or changed) with the raw property; if you want to access it as NUL terminated string, use the value property:

>>>
>>> from ctypes import *>>> p = create_string_buffer(3)      # create a 3 byte buffer, initialized to NUL bytes>>> print sizeof(p), repr(p.raw)3 '\x00\x00\x00'>>> p = create_string_buffer("Hello")      # create a buffer containing a NUL terminated string>>> print sizeof(p), repr(p.raw)6 'Hello\x00'>>> print repr(p.value)'Hello'>>> p = create_string_buffer("Hello", 10)  # create a 10 byte buffer>>> print sizeof(p), repr(p.raw)10 'Hello\x00\x00\x00\x00\x00'>>> p.value = "Hi">>> print sizeof(p), repr(p.raw)10 'Hi\x00lo\x00\x00\x00\x00\x00'>>>

The create_string_buffer() function replaces the c_buffer() function (which is still available as an alias), as well as the c_string() function from earlier ctypes releases. To create a mutable memory block containing unicode characters of the C type wchar_t use the create_unicode_buffer() function.



Sometimes a C api function expects a pointer to a data type as parameter, probably to write into the corresponding location, or if the data is too large to be passed by value. This is also known as passing parameters by reference.

ctypes exports the byref() function which is used to pass parameters by reference. The same effect can be achieved with the pointer() function, althoughpointer() does a lot more work since it constructs a real pointer object, so it is faster to use byref() if you don’t need the pointer object in Python itself:

>>>
>>> i = c_int()>>> f = c_float()>>> s = create_string_buffer('\000' * 32)>>> print i.value, f.value, repr(s.value)0 0.0 ''>>> libc.sscanf("1 3.14 Hello", "%d %f %s",...             byref(i), byref(f), s)3>>> print i.value, f.value, repr(s.value)1 3.1400001049 'Hello'



ctypes.create_string_buffer(init_or_size[size])

This function creates a mutable character buffer. The returned object is a ctypes array of c_char.

init_or_size must be an integer which specifies the size of the array, or a string which will be used to initialize the array items.

If a string is specified as first argument, the buffer is made one item larger than the length of the string so that the last element in the array is a NUL termination character. An integer can be passed as second argument which allows specifying the size of the array if the length of the string should not be used.

If the first parameter is a unicode string, it is converted into an 8-bit string according to ctypes conversion rules.


0 0
原创粉丝点击