gpt4 book ai didi

python-3.x - 如何在 Cython 中使用 memcpy

转载 作者:行者123 更新时间:2023-12-05 03:56:01 25 4
gpt4 key购买 nike

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

错误:

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

我进行了搜索,但没有找到将“memcpy”与原始指针一起使用的示例。

最佳答案

问题是您要添加 c_stringii 的类型是object。在 for 循环之前添加 cdef int i 以强制 i 的类型为 int。

这会为我编译和运行:

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)

关于python-3.x - 如何在 Cython 中使用 memcpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59788251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com