在Go语言中使用可变参数的C函数。

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

Use variadic C functions in Go

问题

我在使用cgo时使用了shm_open函数。在Linux上,shm_open函数有3个参数:

int shm_open(const char *name, int oflag, mode_t mode);

而在OSX(Darwin)上,第三个模式标志是可选的。

int shm_open(const char *name, int oflag, ...);

这在尝试在OSX上传递模式时会导致CGO出现问题。它会抱怨我传递了3个参数,而只期望2个参数。

我该如何解决这个问题?

英文:

I use shm_open with cgo. shm_open is defined with 3 arguments on Linux

int shm_open(const char *name, int oflag, mode_t mode);

whereas on OSX (Darwin) the 3rd mode flag is optional.

int shm_open(const char *name, int oflag, ...);

This creates a problem with CGO when trying to pass a mode on OSX. It complains that I pass 3 arguments, when only 2 are expected.

How can I work around this?

答案1

得分: 6

通常情况下,在发布到SO(Stack Overflow)后的1秒钟内就会有答案。实际上,你可以在CGO注释部分声明函数,所以你只需要使用这样的包装器。

/*
#include <stdio.h>

int shm_open2(const char *name, int oflag, mode_t mode) {
  return shm_open(name, oflag, mode);
}
*/
import "C"
英文:

As usual the revelation comes 1 second after posting to SO. You can actually declare functions in the CGO comment section, so all you have to do is use a wrapper like this.

/*
#include &lt;stdio.h&gt;

int shm_open2(const char *name, int oflag, mode_t mode) {
  return shm_open(name, oflag, mode);
}
*/
import &quot;C&quot;

huangapple
  • 本文由 发表于 2013年11月22日 01:49:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/20128297.html
匿名

发表评论

匿名网友

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

确定