使用空结构体与CGO正确配合使用

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

Using empty struct properly with CGO

问题

使用gssapi.h进行工作

struct gss_name_struct;
typedef struct gss_name_struct * gss_name_t;

我正在尝试弄清楚如何正确初始化包含此内容的变量

var output_name C.gss_name_t = &C.struct_gss_name_struct{}

但是像gss_import_name这样的函数似乎像我传递了空指针。使用CGO正确初始化和使用这些空结构的方法是什么?

英文:

Working with gssapi.h

struct gss_name_struct;
typedef struct gss_name_struct * gss_name_t;

I am trying to figure out how to properly initialize a variable containing this by

var output_name C.gss_name_t = &C.struct_gss_name_struct{}

But the functions like gss_import_name act like if I was passing null pointer to them. What is the correct way to properly initialize and use these empty structs with CGO?

答案1

得分: 5

Go的严格类型使得typedefs很难处理。使你的Go代码看起来清晰的最佳方法是在C中编写一个小的包装函数,以完全按照你想要的方式构建结构体。在这种情况下,Go使用一个零长度的字节数组作为空的C结构体,你可以在下面进行验证。你可以直接在Go中声明它,并在需要时进行转换。

由于C对类型不严格,使用类型推断通常是分配Go期望的类型的最简单方法。还有一个使用cgo工具显示所需类型声明的技巧。使用go tool cgo -godefs filename.go将输出你的类型的cgo定义。正如你所看到的,Go等效的类型可能会有点混乱。

// 在原始的.go文件中的语句
// var output_name C.gss_name_t = &C.struct_gss_name_struct{}

// 从cgo -godefs输出的结果
// var output_name *[0]byte = &[0]byte{}

// 或者更简洁地
output_name := &[0]byte{}

// output_name可以直接转换为C.gss_name_t
fmt.Printf("%+v\n", output_name)
fmt.Printf("%+v\n", C.gss_name_t(output_name))
英文:

Go's strict typing makes typedefs a pain to work with. The best way to make your Go look clear is to write a small wrapper function in C to build the struct exactly how you want it. In this case though, go is using a zero-length byte array for an empty C struct, which you can verify below. You can declare it directly in go, and convert it when necessary.

Since C isn't strict with types, using type inference is often the easiest way to assign the type that Go expects. There's also a trick using the cgo tool to show the type declarations you need. Using go tool cgo -godefs filename.go will output the cgo definitions for your types. As you see though, the go equivalent types could get a little messy.

// statement in the original .go file
//var output_name C.gss_name_t = &C.struct_gss_name_struct{}

// output from cgo -godefs
// var output_name *[0]byte = &[0]byte{}

// or more succinctly
output_name := &[0]byte{}

// output_name can be converted directly to a C.gss_name_t
fmt.Printf("%+v\n", output_name)
fmt.Printf("%+v\n", C.gss_name_t(output_name))

huangapple
  • 本文由 发表于 2014年4月15日 19:11:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/23081990.html
匿名

发表评论

匿名网友

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

确定