donglu9872 2018-08-14 15:37
浏览 119
已采纳

如何使用ctypes将数组从Go [lang]返回到Python?

I am trying to write some code that creates an array in GoLang, and returns it to a python script ctypes (and some numpy). What I have got so far doesn't work, and I cannot figure out why... I would appreciate any help!

My Go code goes something like this:

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

and I am currently trying to import this functionality to python using:

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)

This python function never returns. Other functions from the same library work just fine, but they all return a single float64 (c_double in python).

  • 写回答

1条回答 默认 最新

  • dsieyx2015 2018-08-18 20:46
    关注

    In your code restype is expecting _ndtpr type, see:

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

    See too in numpy document:

    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.

    [others texts]

    In this way lib.Function.restype is pointer type which appropriated type in Golang must be unsafe.Pointer.

    However you want of an slice that need be passed as 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
    }
    

    This cause a problem in Rules for passing pointers between Go and 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

    So you must convert unsafe.Pointer to uintptr golang type.

    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]
    }
    

    In this way you will work fine!

    Note: The structure of slice in C is represented by typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;, but C expect only data, for this is need result only void *data (first field, or field[0]).

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配