dtj4307 2014-02-09 00:21
浏览 16
已采纳

如何提供对使用cgo包装的库的访问权限?

I am trying to write bindings for a C library, specifically the libnfc. My current code is available on Github.

One of the central structures in the libnfc is the device. It is represented by the Go type Device.

type Device struct {
    d *C.nfc_device
} 

All functions inside the libnfc that operate on a Device are methods of it. Now, there are other C libraries (e.g. the libfreefare) whose APIs operates on nfc_devicees. For the sake of modularity, I want to place the code for each library I wrap into its own module. This leads to the problem, that I can't access private structure members from within other modules. I thought about the following solutions:

  • Make d a public member of Device

    This would make it easy to access the underlying nfc_device from within other modules, but it makes it also easy to sidestep type safety. Additionally, I don't know whether cgo recognizes pointers to foreign types if they come from different modules. Finally, I lose flexibility if I change the structure of the Device type.

  • Add an accessor func (Device) GetCPtr() unsafe.Pointer

    This solves the issues above but introduces the new issue that you suddently have access to an unsafe.Pointer in a module that might not even import unsafe.

  • Add an accessor func (Device) GetCPtr() uintptr

    This solves the aforementioned issue, as you have to manually cast the result to get a proper pointer.

Are there any ways I missed? Is there a better, more idiomatic way to provide access to the underlying nfc_device?

  • 写回答

1条回答 默认 最新

  • dongzhen7108 2014-02-09 01:25
    关注

    I'm generally in favour with the third proposal of yours as this is the way the reflect package handles this issue.

    What you could also do is to expose only an interface in your libnfc wrapper, e.g.

    type NFCDevice interface {
        Read() ([]byte, error)
        Write() ([]byte, error)
        // ...
    }
    

    Now you have a public API that is safe.

    Additionally, your device type implements a function

    func (d *device) NfcDevice() *C.nfc_device {
        return d.nfc_device
    }
    

    which you can use in your other wrappers by asserting your NFCDevice to implement the interface

    interface {
        NfcDevice() *C.nfc_device
    }
    

    which you can create on the fly in the other wrappers. This way a programmer has to deliberately do something to access the inner workings of your device.

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

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图