英文:
cgo how to represent go types in c?
问题
在将函数从C语言移植到Go语言时,如果要使用接口类型GoInterface
和整型GoInt
,你需要进行一些调整。以下是你需要进行的更改:
a.h
void *SomeFunc(void *arg);
a.c
void *SomeFunc(void *arg) {
}
a.go
package main
// #include "a.h"
import "C"
type A struct {
}
func main() {
var a = new(A)
}
当你执行go build
时,你可能会遇到以下错误:
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)
对于Go语言是否有类似于Java的jni.h
头文件,你可以使用cgo
工具来实现与C语言的交互。在Go语言中,你可以使用C
包来包含C语言的头文件,并使用C
类型来表示C语言的类型。在这种情况下,你可以直接在a.go
文件中包含a.h
头文件,而无需额外的Go语言头文件。
希望这可以帮助到你!如果你有任何其他问题,请随时提问。
英文:
when export go func to c, the interface type port to GoInterface, and int to GoInt. How to port my c funcs to go with these types?
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)
}
when I go build:
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)
Is there a header file for go like jni.h for java, So I can include there types.
答案1
得分: 2
不,Go语言没有任何方法可以将类型导出为“C可读”。此外,你不能在C语言中引用Go语言的结构体,并且试图将C结构体“伪装成”Go结构体是不安全的,因为你无法控制内存布局。
正确的做法是在C文件中创建一个类型,并将其作为Go结构体的字段添加进去:
// 来自C语言
typedef struct x {
// 字段
} x;
// 在Go语言中,包含定义该类型的.h文件
type X struct {
c C.x
}
然后,通过这种方式操作你的类型,并将C.x
传递给所有的C函数,而不是使用x
。
还有其他几种方法(例如,在需要使用其中一种类型时进行转换),但从一般的角度来看,这种方法是最好的。
编辑:有一些Go类型可以在C语言中表示,例如,通过cgo编译的代码中将定义int64
,但大部分情况下我之前说的仍然适用。
英文:
No, Go doesn't have any way to export types as "C readable". Further, you cannot reference a Go struct from within C, and it is not safe to try and finagle a C struct to "look like" a Go struct since you have no control over memory layout.
The "right" way to do this is to create a type in a C file and add it as a field in the Go struct:
// from C
typedef struct x {
// fields
} x;
// From Go, include your .h file that defines this type.
type X struct {
c C.x
}
Then operate on your type that way, and pass C.x
into all your C functions instead of x
.
There are a couple other ways, (for instance, converting between them any time you want to use it as one or the other), but this one is the best in a vague general sense.
Edit: a FEW Go types can be represented in C, for instance, int64
will be defined in code that's compiled via cgo, but for the most part what I said holds.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论