Last active
April 15, 2018 08:36
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import print_np_as_c | |
arr = np.random.rand(2, 3) | |
print_np_as_c.print_np_as_c(arr) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
void print_array(double * arr, int n) { | |
for(int i = 0; i < n; i++) | |
print("%f\n", arr[i]); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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