Python C / C ++ Extensions: Pass some of the data as np.array to Python (set stride)

View C / C ++ data as np.array from Python.

typedef struct Particle {
  float x[3], v[3];
} Particle;

const int np=10;
Particle* const p= calloc(sizeof(Particle), np);

for(int i=0; i<np; ++i) {
  p[i].x[0]= (float) i + 1;
}

If you want to pass this as np.array to Python, you can use the PyArray_SimpleNewFromData function. [^ 1]

However, here I will show you how to pass only part of the data, x [3], to Python as an np.array. In some cases, your data structure may contain multiple types and not all in one np.array.

If the data does not exist continuously in the memory like this, but they are arranged at regular intervals, you can set strides. [^ 2]

PyObject* PyArray_New(PyTypeObject* subtype, int nd, npy_intp* dims, 
			           int type_num, npy_intp* strides, void* data, 
			           int itemsize, int flags, PyObject* obj);

What is strides []? When ʻais np.array,strides [0]is the byte difference between ʻa [i, j]and ʻa [i + 1, j], strides [][1]is the byte difference between ʻa [i, j]and ʻa [i, j + 1].

static PyObject* py_as_nparray(PyObject *self, PyObject *args)
{
  const int nd=2;
  const int ncol= 3;
  npy_intp dims[]= {np, ncol};
  npy_intp strides[]= {sizeof(Particle), sizeof(float)};

  return PyArray_New(&PyArray_Type, nd, dims, NPY_FLOAT, strides, p->x, 0, 0, 0);
}

Results from Python

import numpy as np
import cext08

a = cext08.as_nparray()

[[  1.   0.   0.]
 [  2.   0.   0.]
 [  3.   0.   0.]
 [  4.   0.   0.]
 ...

The whole code is on github

https://github.com/junkoda/python_c_ext/tree/master/08_nparray_stride

Recommended Posts

Python C / C ++ Extensions: Pass some of the data as np.array to Python (set stride)
Python C / C ++ Extension Pattern-Pass data to Python as np.array
Pass OpenCV data from the original C ++ library to Python
[Introduction to Python] I compared the naming conventions of C # and Python.
[pepper] Pass the JSON data obtained by python request to the tablet.
Pass the path of the imported python module
Try to image the elevation data of the Geographical Survey Institute with Python
Set the process name of the Python program
[Introduction to Data Scientists] Basics of Python ♬
How to pass the execution result of a shell command in a list in Python
Organize Python tools to speed up the initial movement of data analysis competitions
[Introduction to Python] How to get the index of data with a for statement
How to use the C library in Python
Just add the python array to the json data
Set the range of active strips to the preview range
I touched some of the new features of Python 3.8 ①
The story of reading HSPICE data in Python
The transition of baseball as seen from the data
How to read original data or external data on the Internet with scikit-learn instead of attached data set such as iris
"Cython" tutorial to make Python explosive: Pass the C ++ class object to the class object on the Python side. Part 2
[Python] How to calculate the approximation formula of the same intercept 0 as Excel [scikit-learn] Memo
Set the output destination of the execution result to Vim started as a modeless window
Don't take an instance of a Python exception class directly as an argument to the exception class!
It's time to seriously think about the definition and skill set of data scientists
Easy way to check the source of Python modules
python beginners tried to predict the number of criminals
The wall of changing the Django service from Python 2.7 to Python 3
Summary of tools needed to analyze data in Python
Template of python script to read the contents of the file
How to get the number of digits in Python
(Python) Treat integer values as a set of flags
[python] option to turn off the output of click.progressbar
Python points from the perspective of a C programmer
Not being aware of the contents of the data in python
Write data to KINTONE using the Python requests module
[Blender] How to dynamically set the selection of EnumProperty
Specify MinGW as the compiler to use with Python
Let's use the open data of "Mamebus" in Python
Set the specified column of QTableWidget to ReadOnly StyledItemDelegate
14 quizzes to understand the surprisingly confusing scope of Python
Understand the status of data loss --Python vs. R
[Introduction to Python] Basic usage of the library matplotlib
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
Extract the band information of raster data with python
Completely translated the site of "The Hitchhiker's Guide to Python"
Python Note: The mystery of assigning a variable to a variable
I tried to summarize the string operations of Python
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
"Cython" tutorial to make Python explosive: Pass a C ++ class object to a class object on the Python side. Part ①
Return the image data with Flask of Python and draw it to the canvas element of HTML
(Maybe) This is all you need to pass the Python 3 Engineer Certification Data Analysis Exam
How to pass the execution result of a shell command in a list in Python (non-blocking version)
the zen of Python
I tried to find the entropy of the image with python
Try to get the function list of Python> os package
[Python] It might be useful to list the data frames
Make the display of Python module exceptions easier to understand
The story of introducing jedi (python auto-completion package) to emacs
Various ways to calculate the similarity between data in python
(Note) How to pass the path of your own module
The story of rubyist struggling with python :: Dict data with pycall