golang cgo无法通过构建模式c共享导出变量 [英] golang cgo can't export variables by build mode c-shared

查看:78
本文介绍了golang cgo无法通过构建模式c共享导出变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在cgo中开发sudo的插件.

I am trying to develop in the cgo a plug-in of sudo.

https://www.sudo.ws/man/1.8.15/sudo_plugin.man.html

将结构导出到policy_plugin的全局范围.

export the struct to the global scope of policy_plugin.

策略插件必须在全局范围内声明并填充 policy_plugin 结构.

您对此有何解释?

package main

/*
#include "sudo_plugin.h"
#include <stddef.h>
*/
import "C"

func main() {
}

// don't worked
//export policy
var policy = &C.struct_policy_plugin{
    C.SUDO_POLICY_PLUGIN,
    C.SUDO_API_VERSION,
    nil,
    nil,
    nil,
    nil,
    nil,
    nil,
    nil,
    nil,
    nil,
    nil,
}

推荐答案

看来,构建模式 c-shared 仅导出函数条目,而不导出变量.尽管设计文档并未明确指出,但也没有明确提及变量.

It appears buildmode c-shared only exports function entries, not variables. While the design doc does not state this explicitly, it does not talk about variables explicitly either.

cmd/cgo 手册也未明确提及变量,但似乎暗示特殊的//export ... 注释仅适用于函数.

The cmd/cgo manual also does not mention variables explicitly but seems to imply that the special //export ... comments apply to functions only.

您应该做的是在定义并扩展必要的Go函数之后,在C侧声明您的外部变量,如下所示:

What you could supposedly do about this is declare your external variable on the C side—after defining and expoting the necessary Go functions, like this:

"callbacks.go":

"callbacks.go":

package main

import "C"

//export real_fn
func real_fn(x C.int) C.int {
    return 42
}

"main.go":

package main

/*
typedef struct {
    int x;
    int (*fn) (int x);
} foo;

extern int real_fn(int);

foo xyzzy = {
    0,
    real_fn,
};
*/
import "C"

func main() {
}

现在,在运行 go build -buildmode = c-shared 之后,您可以浏览生成的库并在其中看到 xyzzy 符号:

Now after running go build -buildmode=c-shared you can explore the generated library and see the xyzzy symbol available there:

cshared% nm -g cshared | grep -E 'xyzzy|real_fn'
0000000000061330 T _cgoexp_4f8dd74b8333_real_fn
00000000000b42c0 T real_fn
00000000003274d0 D xyzzy

注意:如果要使用回调,则必须将其放入一个或多个单独的文件中-这似乎是 cgo 的怪癖.

A note: if you're about using callbacks you have to put them into a separate file (or files)—this appears to be a quirk of cgo.

这篇关于golang cgo无法通过构建模式c共享导出变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆