如何将numpy数组从Python传递到Golang函数

时间:2018-10-12 18:26:56

标签: python numpy go ctypes

我正在尝试使用Golang创建库以在Python中工作。但是我有一个问题:我不能通过numpy数组去函数。请帮我解决问题。

我的代码:

main.go:

package main

import "C"
import "fmt"

type Matrix [][] int

//export Mass
func Mass(data Matrix) int {
  var sum int=0
  for i, x:= range data {
    for j, _ := range x {
        sum+=data[i][j]
    }
  }
  return sum
}

func main() {
}

例如:

from ctypes import *
import numpy as np

mysum = cdll.LoadLibrary(r'D:\tests\go\sum.dll')

array_2d_int = np.ctypeslib.ndpointer(dtype=c_int32, ndim=2,
                                      flags='CONTIGUOUS')

def mass(a):
    mysum.Mass.argtypes = [array_2d_int]
    mysum.Mass.restype = c_int32
    return mysum.Mass(a)

编译cmd行:

go build -buildmode=c-shared -o sum.dll main.go

当我从dll库调用函数时:

from ex import mass
import numpy as np

a=np.array([[1,2],[3,4]])

print(mass(a))

我有错误:

unexpected fault address 0x1b216000
fatal error: fault
[signal 0xc0000005 code=0x0 addr=0x1b216000 pc=0x6ac92c1f]

goroutine 17 [running, locked to thread]:
....

0 个答案:

没有答案