tags:

views:

50

answers:

2

Hi,

I need to call a c library from my python code. The c library does a lot of image manipulation, so I am passing it image buffers allocated using create_string_buffer.

The problem is that I also need to manipulate and change these buffers. What is the best way to reach in and twiddle individual values in my buffers? The buffers are all uint8 buffers.

Thanks!

+1  A: 

You mean, something like...:

>>> import ctypes
>>> x = ctypes.create_string_buffer('howdy!')
>>> x.value
'howdy!'
>>> x[0] = 'C'
>>> x.value
'Cowdy!'

...?

Alex Martelli
Yes, like that, thanks. But how can I put an integer value in there (i.e. without having to look up the ascii symbol)? For example, if I want to set a byte to 0xff, how could I do that?
Chris
Oh wait, I figured it out:>>> x[0] = "\x43"I was trying this with "xff", but the printout was throwing me off by actually showing "xff". It makes more sense when you print it after using a code for a letter.
Chris
@Chris, if you have a small integer in a variable `i`, `chr(i)` gives you the corresponding 1-byte character; the `struct` and `array` modules offer other ways to convert various types to byte strings.
Alex Martelli
A: 

You may find that Cython is a lot nicer then the ctypes module for melding C libraries with Python code.

Mike Graham
Hmm... that does sound useful. We have a lot of python already written, though, and I don't necessarily want to worry about Cython/Python incompatibilities. But I could build Python-callable modules with Cython, right? Might be an option, and might be a little less crazy when it comes to wrapping these functions.
Chris
Cython modules can be imported from Python; the main use of Cython is to make Python modules that wrap C libraries. Typically you would use Cython to do the wrapping, making a native-feeling API and write the main part of your code using the wrapper you wrote.
Mike Graham