从 Python 调用 Go

我尝试从 python 运行一个简单的 go 脚本,但出现了分段错误。这是我的代码:


主程序


package main


import (

    /*

typedef struct foo{

int a;

int b;

int c;

int d;

int e;

int f;

} foo;

*/

    "C"

)


func main() {}


//export Foo

func Foo(t []int) C.foo {

    return C.foo{}

}

main.py


# loading shared object

lib = cdll.LoadLibrary("main.so")


# go type

class GoSlice(Structure):

    _fields_ = [("data", POINTER(c_void_p)), ("len", c_longlong), ("cap", c_longlong)]


lib.Foo.argtypes = [GoSlice]

lib.Foo.restype = c_void_p


t = GoSlice((c_void_p * 5)(1, 2, 3, 4, 5), 5, 5)

f = lib.Foo(t)

print(f)


有了这个代码,我得到了


140362617287784

[1]    23067 segmentation fault  python3 main.py

现在如果我删除e并f从main.go我得到


None

并且不再出现分段错误。


为什么结构中的成员数量在这里很重要?


[编辑] 两者都在同一位置运行,我运行一个命令clear && go build -o main.so -buildmode=c-shared main.go && python3 main.py


斯蒂芬大帝
浏览 180回答 1
1回答

慕神8447489

您的 GO/C 代码是正确的。问题出在 python 脚本中。该lib.Foo.restype = c_void_p调用需要一个 void 指针,但库返回一个 C 结构。您需要在 python 中定义返回类型 ctypes 结构,然后它将按您的预期工作。main.go :_package mainimport (&nbsp; &nbsp; /*&nbsp; &nbsp; typedef struct foo{&nbsp; &nbsp; int a;&nbsp; &nbsp; int b;&nbsp; &nbsp; int c;&nbsp; &nbsp; int d;&nbsp; &nbsp; int e;&nbsp; &nbsp; int f;&nbsp; &nbsp; } foo;&nbsp; &nbsp; */&nbsp; &nbsp; "C")func main() {}//export Foofunc Foo(t []int) C.foo {&nbsp; &nbsp; foo := C.foo{}&nbsp; &nbsp; foo.a = 1 // setting some values to avoid seeing zeros&nbsp; &nbsp; foo.b = 2&nbsp; &nbsp; return foo}主要.py:from ctypes import *# loading shared objectlib = cdll.LoadLibrary("main.so")# go typeclass GoSlice(Structure):&nbsp; &nbsp; _fields_ = [("data", POINTER(c_void_p)), ("len", c_longlong), ("cap", c_longlong)]class Foo(Structure):&nbsp; &nbsp; _fields_ = [('a', c_int),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ('b', c_int),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ('c', c_int),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ('d', c_int),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ('e', c_int),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ('f', c_int)]lib.Foo.argtypes = [GoSlice]lib.Foo.restype = Foot = GoSlice((c_void_p * 5)(1, 2, 3, 4, 5), 5, 5)f = lib.Foo(t)print(f)print(f.a)print(f.b)然后运行go build -o main.so -buildmode=c-shared main.go && python main.py,会打印:go build -o main.so -buildmode=c-shared main.go && python3 main.py&nbsp;<__main__.Foo object at 0x102608830>12
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go