登录
首页 >  Golang >  Go问答

用 ctypes 如何在 Python 中接收从 Go 返回的数组?

来源:stackoverflow

时间:2024-03-12 13:15:27 138浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《用 ctypes 如何在 Python 中接收从 Go 返回的数组?》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我正在尝试编写一些代码,在 golang 中创建一个数组,并将其返回到 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函数永远不会返回。同一库中的其他函数工作得很好,但它们都返回一个 float64(python 中的 c_double)。


解决方案


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

lib.function.restype = ndpointer(dtype = c_double, shape = (n,))

参见 numpy 文档:

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

[其他文本]

退货

klass:ndpointer类型对象

一个类型对象,它是一个 _ndtpr 实例,包含
dtype、ndim、形状和标志信息。

[其他文本]

这样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 代码在调用返回后可能不会保留 go 指针的副本。

来源: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中切片的结构用 typedef struct { void *data; 来表示。 goint 长度; goint上限; goslice;,但 c 只期望数据,因为这只需要结果 void *data (第一个字段,或字段 [0])。

poc:https://github.com/ag-studies/stackoverflow-pointers-ref-in-golang

终于介绍完啦!小伙伴们,这篇关于《用 ctypes 如何在 Python 中接收从 Go 返回的数组?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>