[英]2d list or array: How do I modify one value - ie a unique pointer per cell?
[英]How do I cast a 2D list to a void pointer and back
我正在嘗試編寫兩個Cython函數來包裝外部函數。 功能是彼此相反的; 一個接受一個字符串,並返回一個帶有兩個字段的結構:一個指向二維數組的空指針(第二個維度總是兩個元素: [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], … ]
),以及數組的長度。 另一個接受相同的結構,並返回一個字符串。 到目前為止,我有以下幾點。 它編譯,但嵌套列表的轉換肯定是不正確的。
我的.pxd
:
cdef extern from "header.h":
struct _FFIArray:
void* data
size_t len
cdef _FFIArray decode_polyline_ffi(char* polyline, int precision);
cdef char* encode_coordinates_ffi(_FFIArray, int precision);
cdef void drop_float_array(_FFIArray coords);
cdef void drop_cstring(char* polyline)
我的.pyx
:
import numpy as np
from pypolyline_p cimport (
_FFIArray,
decode_polyline_ffi,
encode_coordinates_ffi,
drop_float_array,
drop_cstring
)
def encode_coordinates(coords, int precision):
""" coords looks like [[1.0, 2.0], [3.0, 4.0], …] """
cdef double[::1] ncoords = np.array(coords, dtype=np.float64)
cdef _FFIArray coords_ffi
# Wrong
coords_ffi.data = <void*>&ncoords[0]
# Wrong
coords_ffi.len = ncoords.shape[0]
cdef char* result = encode_coordinates_ffi(coords_ffi, precision)
cdef bytes polyline = result
drop_cstring(result)
return polyline
def decode_polyline(bytes polyline, int precision):
cdef char* to_send = polyline
cdef _FFIArray result = decode_polyline_ffi(to_send, precision)
# Wrong
cdef double* incoming_ptr = <double*>(result.data)
# Wrong
cdef double[::1] view = <double[:result.len:1]>incoming_ptr
coords = np.copy(view)
drop_float_array(result)
return coords
我認為問題是你正在嘗試使用2D數組和1D內存視圖
在編碼功能中
# the coords are a 2D, C contiguous array
cdef double[:,::1] ncoords = np.array(coords, dtype=np.float64)
# ...
coords_ffi.data = <void*>&ncoords[0,0] # take the 0,0 element
# the rest stays the same
在解碼功能中
# specify it as a 2D, len by 2, C contiguous array
cdef double[:,::1] view = <double[:result.len,:2:1]>incoming_ptr
# the rest stays the same
(你的FFI函數可能期望Fortran連續數組。在這種情況下, ::1
進入內存視圖的第一維,你也改變incoming_ptr
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.