Last active
May 31, 2019 18:40
-
-
Save synapticarbors/0f9014084994f384c0713dc27be96006 to your computer and use it in GitHub Desktop.
Simple illustration of Cython error
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 as np | |
include_dir = np.get_include() | |
extensions = [ | |
Extension('testlib', ['testlib.pyx', ], include_dirs=[include_dir, ]) | |
] | |
setup( | |
ext_modules=cythonize(extensions) | |
) |
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 testlib | |
print('####################') | |
print('Internally created struct: {} (expected: 1.0)'.format(testlib.foo_test_struct())) | |
print('####################') | |
print('Internally created np array: {} (expected: 1.0)'.format(testlib.foo_test_nparray())) | |
print('####################') | |
print('####################') | |
print('Testing np record from python -> cython') | |
N = 5 | |
dtype = [('x', np.float64), ('y', 'S4'), ('z', np.int64)] | |
x = np.zeros(N, dtype=dtype) | |
x['x'] = np.arange(N).astype(np.float64) + 1 | |
x['y'] = b'ab' | |
x['z'] = np.arange(N, 0, -1) | |
# Set first record to have a string that takes up the entire 4 elements | |
x['y'][0] = 'abcd' | |
# This works | |
print('Externally created np array w/full string: {} (expected: 1.0)'.format(testlib.get_foo_x(x[0]))) | |
# This crashes | |
print('Externally created np array w/full string: {} (expected: 2.0)'.format(testlib.get_foo_x(x[1]))) |
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 | |
cimport numpy as np | |
cdef packed struct foo_type: | |
np.float64_t x | |
char[4] y | |
np.int64_t z | |
cpdef double get_foo_x(foo_type f): | |
return f.x | |
cpdef double foo_test_struct(): | |
cdef: | |
foo_type f | |
f.x = 1.0 | |
for i, c in enumerate(b'ab'): | |
f.y[i] = c | |
f.z = 2 | |
return get_foo_x(f) | |
cpdef double foo_test_nparray(): | |
cdef: | |
foo_type[:] x | |
N = 5 | |
dtype = [('x', np.float64), ('y', 'S4'), ('z', np.int64)] | |
xarr = np.zeros(N, dtype=dtype) | |
xarr['x'] = np.arange(N) + 1.0 | |
xarr['y'] = b'ab' | |
xarr['z'] = np.arange(N, 0, -1) | |
x = xarr | |
return get_foo_x(x[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment