Skip to content

Instantly share code, notes, and snippets.

@nhannguyen95
Last active April 15, 2018 08:36
Show Gist options
  • Save nhannguyen95/3525fde780fad404624a6a8e61cb3e08 to your computer and use it in GitHub Desktop.
Save nhannguyen95/3525fde780fad404624a6a8e61cb3e08 to your computer and use it in GitHub Desktop.
Pass numpy array as C pointers in Cython, ref: https://github.com/cython/cython/wiki/tutorials-NumpyPointerToC
import cython
cimport cython
import numpy as np
cimport numpy as np
cdef extern from "utils.h":
void print_array(double *, int)
def print_np_as_c(np.ndarray[double, ndim=2, mode="c"] arr not None):
cdef int n
n = arr.shape[0] * arr.shape[1]
print_array(&arr[0, 0], n)
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy
setup(
ext_modules = cythonize( [Extension('print_np_as_c',
sources=['print_np_as_c.pyx', 'utils.c'],
include_dirs=[numpy.get_include()],
define_macros=[("NPY_NO_DEPRECATED_API",None)]),
] )
)
# python setup.py build_ext --inplace
import numpy as np
import print_np_as_c
arr = np.random.rand(2, 3)
print_np_as_c.print_np_as_c(arr)
#include <stdio.h>
void print_array(double * arr, int n) {
for(int i = 0; i < n; i++)
print("%f\n", arr[i]);
}
void print_array(double * arr, int n);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment