douyu7210 2013-03-11 13:16
浏览 396
已采纳

Golang(CGO)-任意void *接口

I am wrapping a C library that has a struct with a void* data field that can be used to arbitrarily hold data. What would be the best way (if it's even possible) to wrap this in idiomatic Go?

The struct is quite simply:

typedef struct _Foo {
    void * data;
} Foo;

I was hoping to do something like:

type Foo C.Foo

func (f *Foo) SetData(data interface{}) {
    f.data = unsafe.Pointer(&data)
}

func (f *Foo) Data() interface{} {
    return (interface{})(unsafe.Pointer(f.data))
}

This doesn't work, and is clearly the wrong approach anyways.

I have successfully set a void* data with a length field using a []byte source, but this length-less interface eludes me.

  • 写回答

2条回答 默认 最新

  • doukanzhuo4297 2013-12-28 14:26
    关注

    Coming back to this after several more months of Go under my belt I came up with the following (updated, thanks zupa) solution.

    func (f *Foo) SetData(data interface{}) {
        f.data = unsafe.Pointer(&data)
    }
    
    func (f *Foo) Data() interface{} {
        return unsafe.Pointer(f.data)
    }
    

    And can be used in the following manner:

    type Player struct {
        Name string
    }
    
    p := &Player{
        Name: "Player1",
    }
    
    f.SetData(p)
    
    log.Print(f.Data().(*Player).Name) // Outputs: Player1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?