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_device
es. 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 ofDevice
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 importunsafe
. -
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
?