I'm currently writing some basic cgo code. According to the cgo documention about Go to C references:
To access a struct, union, or enum type directly, prefix it with struct_, union_, or enum_, as in C.struct_stat.
My understanding of this sentence is that if I have a struct named Foo
in C, I have to use the type C.struct_Foo
in Go.
I have written some Go code like:
package main
// #cgo LDFLAGS: -lnavilink -lserialport
// #cgo CFLAGS: -I/usr/local/include
// #include<navilink/navilink.h>
import "C"
import "errors"
func (d *Device) navilinkErrorToGoError() error {
errorC := C.navilink_get_error_description(d.navilinkC)
return errors.New(C.GoString(errorC))
return nil
}
// Device représente une interface
// vers le port série connecté au GPS
type Device struct {
navilinkC *C.struct_NavilinkDevice
}
// Open permettra au développeur d'ouvrir la communication
func (d *Device) Open(path string) error {
res := C.navilink_open_device_from_name(C.CString(path), d.navilinkC)
if res < 0 {
return d.navilinkErrorToGoError()
}
return nil
}
// Close permettra au développeur de fermer la communication
func (d *Device) Close() {
C.navilink_close_device(d.navilinkC)
}
I encounter a compilation error likes:
cannot convert d.navilinkC (type *_Ctype_struct_NavilinkDevice) to type _Ctype_struct___1
The definition of the C struct is the following:
typedef struct {
struct sp_port* serial_port;
struct sp_event_set* event_set;
uint8_t buffer[NAVILINK_MAX_PACKET_SIZE];
NavilinkInformation informations;
int firmware_version;
NavilinkPacket response_packet;
int last_error_code;
} NavilinkDevice;
If I use C.DeviceNavilink
instead of C.DeviceNavilink
as the field's type, the compilation succeeds.
Every C functions expect a pointer to a NavilinkDevice
C struct as last parameter. Code for the C library can be found here
Why does the upper documentation sentence mean since you can refer the C type without using any prefix? What is the difference between both?