书接上回

如果想使用 golang 调用 C++ 代码该如何做?

我们知道,golang 无法直接调用 C++,但是可以调用 C,所以我们需要用 C 包装下 C++ 代码。

还是 C 调用 C++ 类 中 Person 的例子,我们现在要将 person.cpp 的类生成静态库供 golang 调用。

main.chello.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