[Numpy-discussion] C++ class encapsulating ctypes-numpy array?

Matthieu Brucher matthieu.brucher at gmail.com
Thu Mar 20 10:39:20 EDT 2008


2008/3/20, Joris De Ridder <Joris.DeRidder at ster.kuleuven.be>:
>
>
> > You can use ctypes if and ony if the C++ object is only used in one
> > function call. You can't for instance create a C++ container with
> > ctypes, then in Python call some method and then delete the
> > container, because ctypes will destroy the data after the C++
> > container was built. This is the only drawback of ctypes.
>
>
> I'm not sure I understand. Could you perhaps give a pointer for
> additional info, or an example?



Suppose you have a C++ class :

struct MyClass
{
  MyClass(float* data, int dim, ...)
  :container(data, dim)

  void method()
  {
    // Modify container
  }
private:
  MyContainer container;
};

If the MyContainer class wraps the data array without copying it, if in
Python, you wrap it like :

class MyClass:
  def __init__(self, data):
    self._inst = #use a C bridge to create a new MyClass from data

  def method(self):
    wrapMethod(self._inst) #wrapper around method from MyClass

after you create a new Python MyClass, your actual data inside the C++ class
will be freed and thus you have reads or writes errors (and thus can lead to
segmentation faults).


> When it comes to strides, you have to divide them by the size of
> > your data : the stride is counted in bytes and not in short/float/...
>
>
> Yep, I did this on the Python side. Thanks for the remark, though.
>

OK ;)

Matthieu
-- 
French PhD student
Website : http://matthieu-brucher.developpez.com/
Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
LinkedIn : http://www.linkedin.com/in/matthieubrucher
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20080320/783bbdae/attachment.html>


More information about the NumPy-Discussion mailing list