TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Getting C-compatible structs in Go with and for cgo

39 点作者 ash超过 9 年前

4 条评论

bluejekyll超过 9 年前
This just makes the beauty of Rust so much more clear. Compatible C structs without going through this headache. It also points out another reason why Go is not a "systems" language.
评论 #10145791 未加载
评论 #10145464 未加载
parennoob超过 9 年前
From the article:<p>&gt; (By the way, I do mean &#x27;Sysinfo&#x27; here, not &#x27;Cpu_sysinfo&#x27;. Cgo is smart enough to take that sort of commonly seen prefix off of struct field names. I don&#x27;t know what its algorithm is for doing this, but it&#x27;s at least useful.)<p>Anyone know why cgo does this? This seems like an anti-feature to me – if I want fields with prefixes that are different from the C ones, at least make that a knob (and preferably one that isn&#x27;t turned on by default).
laxk超过 9 年前
It is still useless for me if you have struct with &#x27;packed&#x27; attribute ie: <a href="http:&#x2F;&#x2F;lxr.free-electrons.com&#x2F;source&#x2F;fs&#x2F;btrfs&#x2F;ctree.h#L220" rel="nofollow">http:&#x2F;&#x2F;lxr.free-electrons.com&#x2F;source&#x2F;fs&#x2F;btrfs&#x2F;ctree.h#L220</a><p><pre><code> &#x2F;&#x2F; +build ignore package tmp &#x2F;* #include &lt;btrfs&#x2F;ctree.h&gt; *&#x2F; import &quot;C&quot; &#x2F;&#x2F; 220 struct btrfs_disk_key { &#x2F;&#x2F; 221 __le64 objectid; &#x2F;&#x2F; 222 u8 type; &#x2F;&#x2F; 223 __le64 offset; &#x2F;&#x2F; 224 } __attribute__ ((__packed__)); type BtrfsDiskKey C.struct_btrfs_disk_key </code></pre> Output:<p><pre><code> $ go tool cgo -godefs test.go &#x2F;&#x2F; Created by cgo -godefs - DO NOT EDIT &#x2F;&#x2F; cgo -godefs test.go package tmp type BtrfsDiskKey struct { Objectid uint64 Type uint8 Pad_cgo_0 [8]byte } </code></pre> After all the experiments I created my own helper[1], which helps map C structure(even packed) to Go structure using reflect package.<p>[1] <a href="https:&#x2F;&#x2F;github.com&#x2F;plar&#x2F;btrfs&#x2F;blob&#x2F;master&#x2F;ioctl&#x2F;mappings.go" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;plar&#x2F;btrfs&#x2F;blob&#x2F;master&#x2F;ioctl&#x2F;mappings.go</a>
评论 #10146088 未加载
robmccoll超过 9 年前
I wish Go made more of an effort to be more easily C compatible instead of trying to continue breaking away from C.
评论 #10145276 未加载
评论 #10144653 未加载