简体   繁体   English

如何跨操作系统一致地将 C uint64_t 转换为 Cgo?

[英]How to convert C uint64_t to Cgo consistently across OS?

I am using some C library form Go, using cgo to handle the conversion.我正在使用一些 C 库形式 Go,使用 cgo 来处理转换。

I have a C header file that looks like:我有一个 C header 文件,如下所示:

#include <stdlib.h>

typedef struct {
   k uint64_t;
} params;

This structure is used from Go with code like:此结构从 Go 使用,代码如下:

package test

/*
#cgo CFLAGS: -g -Wall
#cgo LDFLAGS: -L. -lmylib -lm -ldl
#include "mylib.h"
*/
import "C"
func NewParams(k uint64) Paramets {
  return Params{
    k:     C.ulonglong(k),
  }
}

The code compiles fine on OS X with Apple clang version 12.0.0, but fails on Linux with clang version 7.1.0, yielding the following error:该代码在带有 Apple clang 版本 12.0.0 的 OS X 上编译良好,但在带有 clang 版本 7.1.0 的 Linux 上编译失败,产生以下错误:

cannot use _Ctype_ulonglong(k) (type _Ctype_ulonglong) as type _Ctype_ulong in field value

If I change the call to C.ulonglong to C.ulong , it works fine on linux but then fails on OS X.如果我将对C.ulong C.ulonglong它在 linux 上工作正常,但在 OS X 上失败。

How can I ensure the same code works on both platform?如何确保相同的代码在两个平台上都有效?

Using go build -work I was able to confirm the issue stems from differences in mapping:使用go build -work我能够确认问题源于映射差异:

  • On the linux side, a C unit64_t gets mapped to a C.ulong在 linux 端,一个 C unit64_t被映射到一个C.ulong
  • On the Mac side, it gets mapped to C.ulonglong在 Mac 端,它被映射到C.ulonglong

Note that both C.ulong and C.ulonglong gets mapped to a go uint64 but using the Go type directly and removing the C.xxx(k) conversion fails. Note that both C.ulong and C.ulonglong gets mapped to a go uint64 but using the Go type directly and removing the C.xxx(k) conversion fails.

Solution is to use C.uint64_t(k) which makes it explicit the size of the type we are talking about.解决方案是使用C.uint64_t(k)这使得它明确我们正在谈论的类型的大小。 This is just fine because the C type is uin64_t anyways.这很好,因为 C 类型无论如何都是uin64_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM