I need to get the data pointer (i.e. the memory offset of the first data byte) of a Python byte string or buffer. I solved it with ctypes:
import ctypes
def get_data_ofs(buf):
import ctypes
data = ctypes.c_char_p()
ctypes.pythonapi.PyObject_AsCharBuffer(ctypes.py_object(buf), ctypes.pointer(data),
ctypes.pointer(ctypes.c_size_t()))
return ctypes.cast(data, ctypes.c_void_p).value
x = 'hello'
if type(zip()) is not list: # Python 3.
def buffer(s, start=0):
return memoryview(s)[start:]
x = bytes(x, 'utf-8')
# The next 3 lines must print the same integer.
print(ctypes.memmove(x, x, 0) + 1)
print(get_data_ofs(x) + 1)
print(get_data_ofs(buffer(x, 1)))
I've verified that my solution (get_data_ofs
) works in Python 2 and 3.
Is there a solution which doesn't use ctypes, or is simpler?