cgo 如何在 c 中表示 go 类型?
cgo how to represent go types in c?
export go func转c时,接口类型port转GoInterface,int转GoInt。如何移植我的 C 函数以与这些类型一起使用?
a.h
void *SomeFunc(GoInterface arg);
a.c
void *SomeFunc(GoInterface arg) {
}
a.go
package main
// #include "a.h"
import "C"
type A struct {
}
func main() {
var a = new(A)
}
当我开始构建时:
cc errors for preamble:
In file included from ./a.go:3:0:
a.h:1:16: error: unknown type name 'GoInterface'
void *SomeFunc(GoInterface arg)
是否有像 jni.h 和 java 一样的头文件,所以我可以在其中包含类型。
不,Go 没有任何方法可以将类型导出为 "C readable"。此外,您 不能 从 C 中引用 Go 结构,并且尝试将 C 结构欺骗 "look like" Go 结构是不安全的,因为您无法控制内存布局。
"right"方法是在 C 文件中创建一个类型并将其作为字段添加到 Go 结构中:
// from C
typedef struct x {
// fields
} x;
// From Go, include your .h file that defines this type.
type X struct {
c C.x
}
然后以这种方式对您的类型进行操作,并将 C.x
传递给所有 C 函数而不是 x
。
还有其他几种方法(例如,在您想要将其用作其中一种时随时在它们之间进行转换),但这种方法在一般意义上是最好的。
编辑:少数 Go 类型可以用 C 表示,例如,int64
将在通过 cgo 编译的代码中定义,但在大多数情况下我所说的都是成立的。
export go func转c时,接口类型port转GoInterface,int转GoInt。如何移植我的 C 函数以与这些类型一起使用?
a.h
void *SomeFunc(GoInterface arg);
a.c
void *SomeFunc(GoInterface arg) {
}
a.go
package main
// #include "a.h"
import "C"
type A struct {
}
func main() {
var a = new(A)
}
当我开始构建时:
cc errors for preamble:
In file included from ./a.go:3:0:
a.h:1:16: error: unknown type name 'GoInterface'
void *SomeFunc(GoInterface arg)
是否有像 jni.h 和 java 一样的头文件,所以我可以在其中包含类型。
不,Go 没有任何方法可以将类型导出为 "C readable"。此外,您 不能 从 C 中引用 Go 结构,并且尝试将 C 结构欺骗 "look like" Go 结构是不安全的,因为您无法控制内存布局。
"right"方法是在 C 文件中创建一个类型并将其作为字段添加到 Go 结构中:
// from C
typedef struct x {
// fields
} x;
// From Go, include your .h file that defines this type.
type X struct {
c C.x
}
然后以这种方式对您的类型进行操作,并将 C.x
传递给所有 C 函数而不是 x
。
还有其他几种方法(例如,在您想要将其用作其中一种时随时在它们之间进行转换),但这种方法在一般意义上是最好的。
编辑:少数 Go 类型可以用 C 表示,例如,int64
将在通过 cgo 编译的代码中定义,但在大多数情况下我所说的都是成立的。