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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With