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.

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

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题