Home > Software design >  bsearch in Cython
bsearch in Cython

Time:09-15

I'm learning cython's libc.bsearch for trying to use Cython to get an index in a sorted array. The example is from this question with modifications:

## 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

I then created a 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()
    ]
)

And compiled the code in Win10 in command prompt: python setup.py build_ext -i. But running it as follows got a strange result:

>>> from test_bsearch import bsearch_c
>>> import numpy as np
>>> x = np.arange(20, dtype=np.int32)
>>> bsearch_c(x, 5)  # got 610183044

I know nothing about C , so can't figure out what's wrong with above implementation. How to correct?

CodePudding user response:

cdef int j = <int> p

This is casting a pointer to an int. You want

cdef int j = p[0]
  • Related