douzhou7656 2019-02-13 09:23
浏览 83
已采纳

如何使用不同包中的相同C类型?

I'm trying to use cairo bindings (Go package), which defines a wrapper structure with a C type in it, with a C function, but can't make it work.

The cairo package defines a Context:

package cairo
...
type Context struct {
    Ptr *C.cairo_t
}
...

Then, from the main package, I want to use its pointer:

package main
...
cr := cairo.Create(surf.Surface)
layout := C.pango_cairo_create_layout(cr.Ptr)
...

The C.pango_cairo_create_layout accepts *C.cairo_t, which is what cr.Ptr should be. However, the go compiler doesn't agree:

./main.go:114:157: cannot use cr.Ptr (type *cairo._Ctype_struct__cairo) as type *_Ctype_struct__cairo in argument to func literal

As can be seen, cr.Ptr is of type *cairo.C.cairo_t and not *C.cairo_t, that is, the package namespace is a part of the type.

I've found https://github.com/golang/go/issues/13467, which talks about a workaround using the combination of the reflect package and unsafe.Pointer. However, I can't make it work.

How do I correctly "bend" this so it compiles and works?

  • 写回答

1条回答

  • duanjia7607 2019-02-15 08:00
    关注

    For those interested, I've figured it out.

    package main
    ...
    cr := cairo.Create(surf.Surface)
    ptr := (*C.cairo_t)(unsafe.Pointer(reflect.ValueOf(cr.Ptr).Pointer()))
    layout := C.pango_cairo_create_layout(ptr)
    ...
    

    Maybe it can be done more simply, but this works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题