[wxPython-users] using wxImage in C++ python extension

Josiah Carlson jcarlson at uci.edu
Wed Aug 16 10:24:24 PDT 2006


Robin Dunn <robin at alldunn.com> wrote:
> 
> Josiah Carlson wrote:
> 
> > No.  The current implementation of buffer keeps a refcounted pointer to
> > the object it has a buffer of, as well as a second pointer to the data
> > (acquired via PyObject_AsBuffer() ).  The data pointer within the object
> > pointed to by buffer changes, and no buffers pointed to the object are
> > updated (to update them would violate various assumptions with how
> > buffers work). This is a long-known issue, and is a major problem with
> > how Python buffers currently work.  The only solution to this requires
> > having a realloc that warns you if it is going to allocate a new block,
> > or strictly over-allocating initially, only ever using malloc, and
> > creating a new data buffer object that holds memory used by array, etc.
> > 
> > The fact that the memory still has what you expect *now*, doesn't mean
> > it will in the future, nor does it mean that you will always be able to
> > access the memory without segfault.  
> 
> And just to tie this explanation back to the original question:  When 
> the buffer is given to the wx.Image then it pulls out the pointer and 
> gives it to the wx.Image.  At that point all the wx.Image knows about is 
> that pointer so if the original Python object moves its buffer to 
> another location in memory then the pointer that the wx.Image currently 
> has will be invalid and it will not be aware that it moved.

Ultimately, if a user wants to use a buffer without copying, one should
be sure that the buffer cannot be moved in memory by design (string) or
by convention.  Note that Python strings can have their contents (not
size) mutated by C code, and will work just fine, as long as one doesn't
explicitly or implicitly use hash() before and after such mutations
(don't let them be keys in a dictionary).  But realize that such
behavior is unsupported.


 - Josiah





More information about the wxpython-users mailing list