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

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条)

相关推荐 更多相似问题