1 回答
TA贡献1780条经验 获得超1个赞
您的 GO/C 代码是正确的。问题出在 python 脚本中。该lib.Foo.restype = c_void_p调用需要一个 void 指针,但库返回一个 C 结构。您需要在 python 中定义返回类型 ctypes 结构,然后它将按您的预期工作。
main.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 {
foo := C.foo{}
foo.a = 1 // setting some values to avoid seeing zeros
foo.b = 2
return foo
}
主要.py:
from ctypes import *
# 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)]
class Foo(Structure):
_fields_ = [('a', c_int),
('b', c_int),
('c', c_int),
('d', c_int),
('e', c_int),
('f', c_int)]
lib.Foo.argtypes = [GoSlice]
lib.Foo.restype = Foo
t = 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
<__main__.Foo object at 0x102608830>
1
2
- 1 回答
- 0 关注
- 170 浏览
添加回答
举报