Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7857747
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T21:08:08+00:00 2026-06-02T21:08:08+00:00

I’m trying to read many values (in sequence) from a large numpy array using

  • 0

I’m trying to read many values (in sequence) from a large numpy array using the C API. I’d like a more efficient way than seperately using boost::python::extract(…) on each value. Something like getting a pointer to the first value and then just incrementing that pointer.

I’ve read through the numpy API docs and I can see that it’s possible but am none the wiser on how to actually accomplish this. Can anyone point me to an example?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T21:08:09+00:00Added an answer on June 2, 2026 at 9:08 pm

    The Boost::Python API does not allow you to do that directly. You can use the Numpy C API to do it. Getting access to the underlying PyObject* can be done using the ptr() method of boost::python::object. Access to the data can be obtained using PyArray_DATA(PyObject*).

    Here’s an example that multiplies a 2d Numpy array by a number. I’ve had some trouble finding out how to compile this on Mac OS (i.e., where the Numpy headers are), so I’ll add this here: running

    import numpy; print numpy.get_include()
    

    in Python gives the correct include path. You can for example use that in a cmake Find module (see this, for example; you’ll have to set the PYTHON_EXECUTABLE variable yourself).

    Update: I modified the code to handle the case in which the input array is not contiguous — this happens for example whenever you use a slice, as in arr[::2, ::2]. The most straightforward way to handle this is to use PyArray_FROM_OTF; do note, however, that this will make a copy of the array unless the array is already in contiguous form. The advantage of this approach is that it can handle the case in which the input is any kind of nested sequence (e.g., a list of lists).

    If your array is so big that you would prefer avoiding making copies of it, you can use PyArray_STRIDES to get the stride information that helps you access the data. From http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html,

    The byte offset of element (i[0], i[1], ..., i[n]) in an array a is:

    offset = sum(np.array(i) * a.strides)

    (note that this is the byte offset, so you should add it to the result of PyArray_BYTES before you cast to final data type; also, this will not help if the array is improperly aligned, or if it has the wrong byte order)

    Here’s the sample code:

    #include <boost/python.hpp>
    
    #include <exception>
    
    #include <numpy/arrayobject.h>
    
    using namespace boost::python;
    
    struct WrongSizeError : public std::exception {
      const char* what() const throw() { return "Unsupported array size."; }
    };
    
    struct WrongTypeError : public std::exception {
      const char* what() const throw() { return "Unsupported array type."; }
    };
    
    // Boost::Python needs the translators
    void translate_sz(const WrongSizeError& e)
    {
      PyErr_SetString(PyExc_RuntimeError, e.what());
    }
    
    void translate_ty(const WrongTypeError& e)
    {
      PyErr_SetString(PyExc_RuntimeError, e.what());
    }
    
    // multiply matrix of double (m) by f
    object multiply(numeric::array m, double f)
    {
      PyObject* m_obj = PyArray_FROM_OTF(m.ptr(), NPY_DOUBLE, NPY_IN_ARRAY);
      if (!m_obj)
        throw WrongTypeError();
    
      // to avoid memory leaks, let a Boost::Python object manage the array
      object temp(handle<>(m_obj));
    
      // check that m is a matrix of doubles
      int k = PyArray_NDIM(m_obj);
      if (k != 2)
        throw WrongSizeError();
    
      // get direct access to the array data
      const double* data = static_cast<const double*>(PyArray_DATA(m_obj));
    
      // make the output array, and get access to its data
      PyObject* res = PyArray_SimpleNew(2, PyArray_DIMS(m_obj), NPY_DOUBLE);
      double* res_data = static_cast<double*>(PyArray_DATA(res));
    
      const unsigned size = PyArray_SIZE(m_obj); // number of elements in array
      for (unsigned i = 0; i < size; ++i)
        res_data[i] = f*data[i];
    
      return object(handle<>(res)); // go back to using Boost::Python constructs
    }
    
    BOOST_PYTHON_MODULE(test)
    {
      // register exception translators
      register_exception_translator<WrongSizeError>(&translate_sz);
      register_exception_translator<WrongTypeError>(&translate_ty);
    
      // tell Boost::Python under what name the array is known
      numeric::array::set_module_and_type("numpy", "ndarray");
      def("multiply", multiply);
    
      // initialize the Numpy C API
      import_array();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm making a simple page using Google Maps API 3. My first. One marker
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.