[英]Cgo: How to return double array from C to Go
我有一個這樣的 C 函數
double* c_func(int n_rows) {
double result[n_rows];
for (int i = 0; i < n_rows; ++i) {
result[i] = (double)i;
}
return result;
}
我使用這個 Go 函數來處理 C double:
// convert C double pointer to float64 slice ...
func doubleToFloats(in *C.double, length int) []float64 {
out := make([]float64, length, length)
start := unsafe.Pointer(in)
size := unsafe.Sizeof(C.double(0))
for i := 0; i < length; i++ {
val := *(*C.double)(unsafe.Pointer(uintptr(start) + size*uintptr(i)))
out[i] = float64(val)
}
return out
}
這有時有效,但有時無效。 當它不起作用時,它返回如下內容:
[0 1 2 3 4 5 6 7 8 9 10 2.53e-321 3.32018606e-316 4.24664374149e-312 4.24399158193e-312 1.1383e-320 3.31882387e-316 3.71924634e-316 3.31885594e-316 3.71924634e-316 5e-324 0 4.6950308e-316 4.24664374149e-312 3.7175681e-316 3.3200616e-316]
對我來說這看起來有點記憶問題......
我不確定這是否是在 Go 中處理從 C 返回的雙數組的正確方法。 如果是,如何解決問題(偶爾發生)。 如果不是,處理從 C 返回的雙數組的正確方法是什么?
謝謝。
在 C 中,您返回的那個指針將是陳舊的。 您需要像 double *result = calloc(sizeof(double), nrows) 一樣分配表——這也需要有一種釋放內存的方法。
好的,所以我想出了一個簡單的方法來實現這一目標。
我們首先使用calloc
為數組分配內存:
double* c_func(int n_rows) {
double* result;
result = calloc(n_rows, sizeof(double));
for (int i = 0; i < n_rows; ++i) {
result[i] = (double)i;
}
return result;
}
之后,我們只需在 Go 中將數據轉換為正確的類型。 訣竅是使用C.free
來釋放從 C 端分配的內存。
// convert C double pointer to float64 slice ...
func doubleToFloats(in *C.double, size int) []float64 {
defer C.free(unsafe.Pointer(in))
out := (*[1 << 30]float64)(unsafe.Pointer(in))[:size:size]
return out
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.