cgo how to represent go types in c?

huangapple go评论88阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年10月20日 08:31:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/33226125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定