3
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.

JeffQ
  • 94
  • 5
  • 1
    Did you cimport `memcpy`? If you did, add this to your example, otherwise cimport `memcpy`. – ead Jan 17 '20 at 13:30

1 Answers1

3

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) 
Stephen
  • 2,613
  • 1
  • 24
  • 42