Created
August 1, 2012 23:40
-
-
Save npinto/3231603 to your computer and use it in GitHub Desktop.
Cython 0.16 C++ Demo
This file contains 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
*.so | |
_demo.cpp | |
build |
This file contains 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
# 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) |
This file contains 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 <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; | |
} |
This file contains 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
namespace demo { | |
int test(float* arr, int size); | |
} |
This file contains 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.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