Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use memcpy in Cython

with open(fname, 'rb') as fp:
    line = fp.readline().strip()
    content = fp.read()
cdef int nb = len(content)
#print("Hello ", nb)
cdef char* c_string = <char *> malloc((nb + 1) * sizeof(char))
cdef char* tmp_str = <char *> malloc(4)
memcpy(tmp_str, c_string + 8, 4)
print(atof(tmp_str))    # this line is ok
for i in range(nb):
    memcpy(tmp_str, c_string + i, 4)  # error occur
    # print(atof(tmp_str))

Error:

    for i in range(nb):
    memcpy(tmp_str, c_string + i, 4)`
                            ^       `
decodex.pyx:23:33: Cannot convert Python object to 'const void *'`

I searched but find no example that use "memcpy" with raw pointer.

like image 439
qinshuo Avatar asked Nov 24 '25 10:11

qinshuo


1 Answers

The problem is that you are adding c_string and i. The type of i is object. Add cdef int i right before your for loop to force the type of i to be an int.

This compiles and runs for me:

In [1]: !echo "some text\nfor the file" > foo.txt                                                                                                                                              

In [2]: %load_ext cython                                                                                                                                                                       

In [3]: %%cython 
...: from libc.stdlib cimport malloc 
...: from libc.string cimport memcpy 
...: from libc.stdlib cimport atof 
...:  
...: with open('foo.txt', 'rb') as fp: 
...:     line = fp.readline().strip() 
...:     content = fp.read() 
...: cdef int nb = len(content) 
...: #print("Hello ", nb) 
...: cdef char* c_string = <char *> malloc((nb + 1) * sizeof(char)) 
...: cdef char* tmp_str = <char *> malloc(4) 
...: memcpy(tmp_str, c_string + 8, 4) 
...: print(atof(tmp_str))    # this line is ok 
...: cdef int i 
...: for i in range(nb): 
...:     memcpy(tmp_str, c_string + i, 4) 
like image 87
Stephen Avatar answered Nov 27 '25 00:11

Stephen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!