cgo
golang是類C的語言 支持調(diào)用C接口(不支持調(diào)用C++)
Go調(diào)用C/C++的方式 :
- C : 直接調(diào)用C API
- C++ : 通過實(shí)現(xiàn)一層封裝的C接口來調(diào)用C++接口
Go集成C/C++的方式
- go的源代碼中直接聲明C代碼
比較簡(jiǎn)單的應(yīng)用情況 可以直接使用這種方法 C代碼直接寫在go代碼的注釋中
注釋之后緊跟import "C" 通過C.xx來引用C的結(jié)構(gòu)和函數(shù)
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"
"sync"
)
func main() {
var ctx *C.ctx = C.createCtx(100)
fmt.Printf("id : %d\n", ctx.id)
}
- 通過封裝實(shí)現(xiàn)調(diào)用C++接口
目錄結(jié)構(gòu) :C++代碼放置在cpp目錄下
C++代碼需要提前編譯成動(dòng)態(tài)庫(拷貝到系統(tǒng)庫目錄可以防止go找不到動(dòng)態(tài)庫路徑),go程序運(yùn)行時(shí)會(huì)去鏈接
.
├── cpp
│ ├── cwrap.cpp
│ ├── cwrap.h
│ ├── libgotest.dylib
│ ├── test.cpp
│ └── test.h
├── main.go
test.cpp和test.h是C++接口的實(shí)現(xiàn)
cwrap.h和cwrap.cpp是封裝的C接口的實(shí)現(xiàn)
- test.h
#ifndef __TEST_H__
#define __TEST_H__
#include <stdio.h>
class Test {
public:
void call();
};
#endif
- test.cpp
#include "test.h"
void Test::call() {
printf("call from c++ language\n");
}
- cwrap.cpp
#include "cwrap.h"
#include "test.h"
void call() {
Test ctx;
ctx.call();
}
- cwrap.h
#ifndef __CWRAP_H__
#define __CWRAP_H__
#ifdef __cplusplus
extern "C" {
#endif
void call();
#ifdef __cplusplus
}
#endif
#endif
- main.go
package main
/*
#cgo CFLAGS: -Icpp
#cgo LDFLAGS: -lgotest
#include "cwrap.h"
*/
import "C"
func main() {
C.call()
}