我正在学习Cython的libc.bsearch,因为它试图使用Cython获取排序数组中的索引。该示例来自这个问题,并进行了修改:
## test_bsearch.pyx
cimport cython
from libc.stdlib cimport bsearch
cdef int comp_fun(const void *a, const void *b) nogil:
cdef int a_v = (<int*>a)[0]
cdef int b_v = (<int*>b)[0]
if a_v < b_v:
return -1
elif a_v > b_v:
return 1
else:
return 0
def bsearch_c(int[::1] t, int v):
cdef int *p = <int*> bsearch(&v, &t[0], t.shape[0], sizeof(int), &comp_fun)
cdef int j = <int> p
if p != NULL:
return j
else:
return -1然后我创建了一个setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules=cythonize([
"test_bsearch.pyx"
],
compiler_directives={'language_level': "3"}
),
include_dirs=[
np.get_include()
]
)并在命令提示符:Win10中编译了代码:python setup.py build_ext -i。但是,按照以下方式运行它得到了一个奇怪的结果:
>>> from test_bsearch import bsearch_c
>>> import numpy as np
>>> x = np.arange(20, dtype=np.int32)
>>> bsearch_c(x, 5) # got 610183044我对C++一无所知,所以不知道上面的实现有什么问题。如何纠正?
发布于 2022-09-15 11:20:43
cdef int j = <int> p这是一个指向int的指针。你想要的
cdef int j = p[0]https://stackoverflow.com/questions/73728167
复制相似问题