什么是等效于结构的const指针的cgo类型?

时间:2017-06-22 17:37:37

标签: go cgo

我在C中有一个外部函数decalred:

//extern void goCallback(const struct libvlc_event_t*, void*);

go中定义:

//export goCallback
func goCallback(event unsafe.Pointer, userData unsafe.Pointer) {
    log.Fatal("TODO goCallback")
}

编译代码时,我遇到类型冲突的错误

# github.com/tarrsalah/libvlc-go
In file included from $WORK/github.com/tarrsalah/libvlc-go/_obj/_cgo_export.c:3:0:
cgo-gcc-export-header-prolog:42:13: error: conflicting types for ‘goCallback’
In file included from $WORK/github.com/tarrsalah/libvlc-go/_obj/_cgo_export.c:3:0:
../../../tarrsalah/libvlc-go/event_manager.go:6:13: note: previous declaration of ‘goCallback’ was here
 //extern void goCallback(const struct libvlc_event_t*, void*);
             ^~~~~~~~~~
/tmp/go-build855229382/github.com/tarrsalah/libvlc-go/_obj/_cgo_export.c:17:6: error: conflicting types for ‘goCallback’
 void goCallback(void* p0, void* p1)
      ^~~~~~~~~~
In file included from $WORK/github.com/tarrsalah/libvlc-go/_obj/_cgo_export.c:3:0:
../../../tarrsalah/libvlc-go/event_manager.go:6:13: note: previous declaration of ‘goCallback’ was here
 //extern void goCallback(const struct libvlc_event_t*, void*);
             ^~~~~~~~~~

go相当的const struct libvlc_event_t*是什么?

1 个答案:

答案 0 :(得分:1)

使用typedef为结构创建类型别名,如下所示:

/*

typedef const struct libvlc_event_t clibvlc_event_t;
extern void goCallback(clibvlc_event_t*, void*);
*/
import "C"

//export goCallback
func goCallback(event *C.clibvlc_event_t, userData unsafe.Pointer) {
    log.Fatal("TODO goCallback")
}

如果您想了解与go兼容的C.clibvlc_event_t类型定义,请使用cgo选项运行-godefs,即

go tool cgo -godefs <YOUR-GO-FILE>

例如,如果结构定义为https://docs.libreoffice.org/avmedia/html/Types_8hxx_source.html

struct libvlc_event_t
{
    int   type;  // event type
    void *p_obj; // object emitting that event

    union // so far we don't need this.
    {
     struct {
        const char *dummy1;
        const char *dummy2;
      } padding;
    } u;
};

然后,go中的兼容结构将是:

type VLCEvent struct {
    Type      int32
    Pad_cgo_0 [4]byte
    Obj       *byte
    U         [16]byte
}

//Cast C struct to Go struct
ev := (*VLCEvent)(unsafe.Pointer(event))

//Cast Go struct to C struct
p := (*C.clibvlc_event_t)(unsafe.Pointer(&VLCEvent{}))

修改
添加示例结构。