create_string_buffer how to get used size
-
15-06-2021 - |
Frage
How can I determine the used size/length of a buffer created with create_string_buffer?
buffer = create_string_buffer(1000)
e.g. in buffer I have 3 values and 997 unused -> how it's possible to get the 3?
Lösung
Is there any reason you can't just do len(buffer.value)
?
For pure theoretical fun of it -- I see no reason to do this if you can use the above method -- I'll mention that you can also do buffer.raw.find("\x00")
or list(buffer).index("\x00")
. These fail if the string is not properly null-terminated though.
Andere Tipps
In [1]: from ctypes import *
In [2]: s = create_string_buffer(1000)
In [3]: s[0] = '1'
In [4]: s[1] = '2'
In [5]: s[2] = '3'
In [6]: s
Out[6]: <ctypes.c_char_Array_1000 at 0x8ca126c>
In [7]: for i, c in enumerate(s):
...: if c == '\x00':
...: break
...:
In [8]: i
Out[8]: 3
C-Strings are null-terminated, so loop over the string until you find '\x00'.
You could:
- Have the function populating the buffer return the amount of buffer used.
- Look for a terminating condition of the buffer such as nul.
- Initialize the buffer with a value never used in the data, then look for that terminating the data.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow