import "C"
,通過C.xx
來參照C語言的結構和函數,如下所示:package main /* #include <stdio.h> #include <stdlib.h> typedef struct { int id; }ctx; ctx *createCtx(int id) { ctx *obj = (ctx *)malloc(sizeof(ctx)); obj->id = id; return obj; } */ import "C" import ( "fmt" ) func main() { var ctx *C.ctx = C.createCtx(100) fmt.Printf("id : %dn", ctx.id) }執行結果如下:
go run main.go
id : 100
├── cpp
│ ├── cwrap.cpp
│ ├── cwrap.h
│ ├── test.cpp
│ └── test.h
└── main.go
#ifndef __TEST_H__ #define __TEST_H__ #include <stdio.h> class Test { public: void call(); }; #endif
#include "test.h" void Test::call() { printf("call from c++ languagen"); } cwrap.cpp #include "cwrap.h" #include "test.h" void call() { Test ctx; ctx.call(); }
#ifndef __CWRAP_H__ #define __CWRAP_H__ #ifdef __cplusplus extern "C" { #endif void call(); #ifdef __cplusplus } #endif #endif
package main /* #cgo CFLAGS: -Icpp #cgo LDFLAGS: -lgotest #include "cwrap.h" */ import "C" func main() { C.call() }