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 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥20 Python安装cvxpy库出问题
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题