英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论