Skip to content

Instantly share code, notes, and snippets.

@npinto
Created August 1, 2012 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npinto/3231603 to your computer and use it in GitHub Desktop.
Save npinto/3231603 to your computer and use it in GitHub Desktop.
Cython 0.16 C++ Demo
*.so
_demo.cpp
build
# distutils: language = c++
# distutils: sources = demo.cpp
cdef extern from "demo.h" namespace "demo":
cdef int test(float*, int)
import numpy as np
cimport numpy as cnp
def func(cnp.ndarray[cnp.float32_t, ndim=1] arr,
size=1,
):
assert arr.dtype == 'float32'
ptr = arr.data
return test(<float*>arr.data, <Py_ssize_t>size)
#include <iostream>
#include "demo.h"
using namespace std;
int demo::test(float* arr, int size)
{
int i;
for(i=0; i < size; ++i)
cout << i << ":" << ((float*)arr)[i] << endl;
return i;
}
namespace demo {
int test(float* arr, int size);
}
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
setup(
ext_modules=[
Extension("_demo",
sources=["_demo.pyx", "demo.cpp"],
language="c++",
include_dirs=[np.get_include()],
),
],
cmdclass={'build_ext': build_ext}
)
import _demo
arr = np.random.randn(10).astype('f')
print _demo.func(arr, size=len(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment