1. 程式人生 > >Golang 通過 cgo 呼叫 C/C++ 靜態庫(二)

Golang 通過 cgo 呼叫 C/C++ 靜態庫(二)

書接上回

如果想使用 golang 呼叫 C++ 程式碼該如何做?

我們知道,golang 無法直接呼叫 C++,但是可以呼叫 C,所以我們需要用 C 包裝下 C++ 程式碼。

還是 C 呼叫 C++ 類 中 Person 的例子,我們現在要將 person.cpp 的類生成靜態庫供 golang 呼叫。

我們首先將 main.c 修改和封裝下,名字叫 hello.c

void *Create() {
  return call_Person_Create
(); } void Destroy(void *p) { call_Person_Destroy(p); } const char *GetName(void *p) { return call_Person_GetName(p); } int GetAge(void *p) { return call_Person_GetAge(p); }

然後將介面在 hello.h 中宣告下:

#ifdef __cplusplus
extern "C" {
#endif

extern void *Create();
extern void Destroy(void *p)
; extern const char *GetName(void *p); extern int GetAge(void *p); #ifdef __cplusplus } #endif

編譯成靜態庫:

g++ -Wall -c person.cpp wrapper.cpp
gcc -Wall -c hello.c
ar -crsv libhello.a *.o

go 程式呼叫如下:

package main

/*
#cgo CFLAGS: -I${SRCDIR}/cpp
#cgo LDFLAGS: -L${SRCDIR}/cpp -lhello -lstdc++
#include <stdio.h>
#include <stdlib.h>
#include "hello.h"
*/
import "C" import ( "fmt" ) func main() { p := C.Create() name := C.GoString(C.GetName(p)) age := C.GetAge(p) C.Destroy(p) fmt.Printf("Name is %s, age is %d\n", name, age) }

注意:

  • -lstdc++ 要放在 -lhello 之後

完整程式碼地址 https://github.com/alandtsang/godemo/tree/master/cgo/callcpp