Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ctypes and pointer manipulation

Tags:

python

ctypes

I am dealing with image buffers, and I want to be able to access data a few lines into my image for analysis with a c library. I have created my 8-bit pixel buffer in Python using create_string_buffer. Is there a way to get a pointer to a location within that buffer without re-creating a new buffer? My goal is to analyze and change data within that buffer in chunks, without having to do a lot of buffer creation and data copying.

In this case, ultimately, the C library is doing all the manipulation of the buffer, so I don't actually have to change values within the buffer using Python. I just need to give my C function access to data within the buffer.

like image 694
Chris Avatar asked Mar 22 '10 17:03

Chris


People also ask

What does ctypes do in Python?

ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

Does ctypes work with C++?

ctypes is a foreign function library for Python that provides C compatible data types. Although it is mostly used to consume C and C++ libraries, you can use ctypes with libraries written in any language that can export a C compatible API, e.g. Fortran, Rust.


1 Answers

create_string_buffer gives you a ctypes object (an array of chars), then byref, and I quote,

Returns a light-weight pointer to obj, which must be an instance of a ctypes type. offset defaults to zero, and must be an integer that will be added to the internal pointer value.

The offset argument has been added in 2.6, so if you're stuck with an older version you will unfortunately need more work.

like image 64
Alex Martelli Avatar answered Sep 24 '22 00:09

Alex Martelli