Skip to content

Instantly share code, notes, and snippets.

@YukiSakamoto
Created September 12, 2012 11:21
Show Gist options
  • Select an option

  • Save YukiSakamoto/3706035 to your computer and use it in GitHub Desktop.

Select an option

Save YukiSakamoto/3706035 to your computer and use it in GitHub Desktop.
pass numpy-object into C modules via cython
#include <stdio.h>
void listup(int *array, int size)
{
int i;
for(i = 0; i < size; i++) {
printf("%d\n", *(array + i));
}
}
void listup(int *array, int size);
python setup.py build_ext --inplace
import numpy as np
cimport numpy as np
cdef extern from "clistup.h":
void listup(int*,int)
cdef call_org_listup(np.ndarray py_array):
cdef int *int_array = <int*>py_array.data
cdef int length = len(py_array)
listup(int_array,length)
def listup_array(np_array):
call_org_listup(np_array)
import numpy as np
import Listup
zero_array = np.zeros(5)
Listup.listup_array(zero_array)
print "=================================="
ar2 = np.array([1000, 1000, 1200, 1500], np.int32)
Listup.listup_array(ar2)
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
source = ['./clistup.c', './listup.pyx']
# mac XXX ここは環境に合わせて変える
numpy_include = ['/System/Library/Frameworks/Python.framework/Versions/Current/Extras/lib/python/numpy/core/include']
setup(
cmdclass = dict(build_ext = build_ext),
ext_modules = [
Extension(
'Listup',
source,
include_dirs = numpy_include,
)
]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment