문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top