以下是我遇到此问题的代码:
cpdef object encode_file(object fin, str fout):
if not PyObject_CheckBuffer(fin):
raise TypeError("fin must follow the buffer protocol")
cdef Py_buffer in_view
cdef int ret_code = PyObject_GetBuffer(fin, &in_view, PyBUF_SIMPLE)
if ret_code < 0:
raise TypeError("Couldn't get buffer from fin")
cdef bytes py_filename = fout.encode()
cdef char* cy_filename = py_filename
cdef bytes py_mode = "w".encode()
cdef const char* mode = py_mode
cdef FILE* fd = fopen(<const char*>py_filename, <const char*>mode)
if <size_t>fd == 0:
raise FileNotFoundError(fout)
cdef unsigned char out_buff[256]
cdef size_t written = 0
cdef size_t total_written = 0
cdef size_t used = 0
cdef size_t total_used = 0
cdef size_t pad_start = 80
cdef unsigned char[:] char_view = fin
cdef unsigned char* char_slice
while total_used < <size_t>in_view.len:
char_view = char_view[used:]
# This is the place where I get the error
char_slice = char_view.buf
used = encode_buffer(
char_slice,
in_view.len - used,
out_buff,
256,
pad_start,
80,
&written,
)
pad_start = 80 - used % 80
total_written += written
total_used += used
if fwrite(out_buff, sizeof(char), used, fd) != used:
fclose(fd)
raise Exception(
"Couldn't write to file: {}. Bytes written: {}".format(
fout, total_used,
),
)
fclose(fd)
print "used: {}, written: {}".format(used, total_written)
return total_written
对于一个简单的例子来说,这可能有点太多的代码,但如果你仔细想想,它真的没有那么多。循环之前的部分处理过滤掉各种边缘情况——它们对这个问题不感兴趣。唯一重要的部分是第一个参数必须实现缓冲区协议,第二个参数是文件名。
因此,为了写入文件,我想获取一片内存视图,然后将其传递给一个 C 函数,该函数需要一个指向unsigned char
. 对于我的一生,我无法弄清楚如何使用 Cython 来做到这一点......我尝试了上面代码的各种排列,但是,在大多数情况下,我得到了
存储临时 Python 引用的不安全 C 派生
没有任何暗示它试图生成什么。
上面的代码也有一些重复,因为我不知道如何使用in_view.buf[x]
它并让它具有我需要的类型。我把它留在这里只是为了表明我也尝试过。
对类似问题的答案不起作用,因为 Cython 内存视图有错误。我会很感激一个不同的答案。