Skip to content

Simple example for exchanging ndarrays between Python and C++ extension #6

Closed

Description

@Kameshkk

I've been searching for a simple example that shows how to exchange NumPy arrays between Python and an extension module written in C++ w/ Boost Python.

Let's make it a bit more concrete. How would you do the following:

  1. Create a NumPy array in Python
  2. Import extension module written in C++ with Boost Python and pass the array to a function in the module
  3. The function does some simple operation on the array -- say square each element -- and returns the modified array, perhaps with a different size, to Python.

Also, if my C++ mostly needs data as vector< vector< double > >or double **, would using the ndarray interface in the C-code incur a lot of performance overhead?

Activity

  1. TallJimbo commented on May 12, 2012

    @TallJimbo
    Member

    You might want to check out libs/examples/gaussian.cpp, which does a little more than this (it uses Boost.NumPy to create converters for a custom matrix/vector type), but still has a lot of the same code.

    I'll get to work adding another, simpler example. In the meantime, to answer your question about overhead:

    • If you use the ndarray interface to extract the data pointer, shape, and strides, and then increment those yourself, there's essentially no overhead at all relative to using the NumPy C-API. If you use it to index each element, the overhead is essentially one non-inlined function call per access.
    • Using vector< vector< double > > is going to require copying all the data in the area no matter what interface you use.
  2. TallJimbo commented on May 13, 2012

    @TallJimbo
    Member

    Please check out libs/numpy/example.cpp to see if it matches what you're looking for.

  3. Kameshkk commented on May 14, 2012

    @Kameshkk
    Author

    Excellent! Thanks a bunch!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions