如何使用 ctypes return 从 Go[lang] 到 Python 的数组?

How to return an array from Go[lang] to Python using ctypes?

我正在尝试编写一些在 GoLang 中创建数组的代码,并将其 return 发送到 python 脚本 ctypes(和一些 numpy)。到目前为止我得到的东西不起作用,我不知道为什么......我将不胜感激任何帮助!

我的 Go 代码是这样的:

func Function(physics_stuff... float64,  N int ) []float64{
    result := make([]float64, N)
    for i:= 0; i< N; i++{
        result[i] =  blah....
    }
    return result;
}

我目前正在尝试将此功能导入 python 使用:

from ctypes import c_double, cdll, c_int
from numpy.ctypeslib import ndpointer

lib = cdll.LoadLibrary("./go/library.so")
lib.Function.argtypes = [c_double]*6 + [c_int]

def lovely_python_function(stuff..., N):
    lib.Function.restype = ndpointer(dtype = c_double, shape = (N,))
    return lib.Function(stuff..., N)

此 python 函数永远不会 return。来自同一个库的其他函数工作得很好,但它们都是 return 一个 float64 (c_double in python).

在您的代码中 restype 需要 _ndtpr 类型,请参阅:

lib.Function.restype = ndpointer(dtype = c_double, shape = (N,))

在numpy文档中也可以看到:

def ndpointer(dtype=None, ndim=None, shape=None, flags=None)

[others texts]

Returns

klass : ndpointer type object

A type object, which is an _ndtpr instance containing
dtype, ndim, shape and flags information.

[其他文字]

这样lib.Function.restype就是指针类型,在Golang中占用的类型必须是unsafe.Pointer

但是你想要一个需要作为指针传递的切片:

func Function(s0, s1, s2 float64, N int) unsafe.Pointer {
    result := make([]float64, N)
    for i := 0; i < N; i++ {
        result[i] = (s0 + s1 + s2)
    }
    return unsafe.Pointer(&result)//<-- pointer of result
}

这会导致 Go 和 C 之间传递指针的规则出现问题

  1. C code may not keep a copy of a Go pointer after the call returns.

Source: https://github.com/golang/proposal/blob/master/design/12416-cgo-pointers.md

所以你必须将unsafe.Pointer转换成uintptr golang类型。

func Function(s0, s1, s2 float64, N int) uintptr {
    result := make([]float64, N)
    for i := 0; i < N; i++ {
        result[i] = (s0 + s1 + s2)
    }
    return uintptr(unsafe.Pointer(&result[0]))//<-- note: result[0]
}

这样你就可以工作了!

注:C中slice的结构用typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;表示,但C只期望数据,因为这是只需要结果void *data(第一个字段,或字段 [0])。

PoC:https://github.com/ag-studies/Whosebug-pointers-ref-in-golang