dth42345 2016-03-25 00:27
浏览 74

golang cgo无法通过构建模式c共享导出变量

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

export the struct to the global scope of policy_plugin.

A policy plugin must declare and populate a policy_plugin struct in the global scope.

Do you have an explanation of what that means?

export_test.go

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,
}
  • 写回答

1条回答 默认 最新

  • douran7929 2016-03-25 17:27
    关注

    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.

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

    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":

    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() {
    }
    

    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
    

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来