?? 1,将c++ 的方法提取到头文件.h中( ) 2,编译cc(c++)文件为动态链接库so文件 3,将头文件放入include目录 .so放入lib目录 4,Go程序中指定 CFLAGS 和 LDFLAGS #cgo CFLAGS: -I ./include #cgo LDFLAGS: -L .b -lhello -Wl,-rpath,/usr/localb 5,运行发布时候指定 export LD_LIBRARY_PATH="lib文件所在目录" (`pwd`) 目录结构:
编译为so文件 g++ -g -Wall -lssl -lcrypto -c decrypter.cc -fPIC -shared -o libdecrypter.so
go文件: package main /* #cgo CFLAGS: -I ./include #cgo LDFLAGS: -L ./lib -lhello #include "hello.h" */ import "C" func main() { C.hello(C.CString("call C hello func")) } hello.c #include "hello.h" #include <stdio.h> void hello(const char *str) { printf("%s(%d): %s\n", __FUNCTION__, __LINE__, str); } hello.h #ifndef ___HELLO___ #define __HELLO___ void hello(const char *str); #endif
编译: go build main.go 编译如果出错: # command-line-arguments /tmp/go-build471704263/command-line-arguments/_obj/xx.cgo2.o: In function `_cgo_7f644bb4ca7c_Cfunc_xxxx': 请一定检查so文件是否为libxxx.so 编译如果报错 could not determine kind of name for C.xxx 请检查 import "C" 是不是紧挨着 go顶部头文件c++ 部分注释代码 运行: ./main 运行如果出现: error while loading shared libraries: xxx.so: cannot open shared object file: No such file or directory 请一定要 export LD_LIBRARY_PATH="动态链接文件所在目录"
其他说明:golang的注释中直接写函数内容的方式只支持c不支持C++ package main
//!!!!以下为c代码不支持c++
/*
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void hello(const char *str)
{
printf("===> %s(%d): %s\n", __FUNCTION__, __LINE__, str);
}
*/
import "C"
func main() {
C.hello(C.CString("call C hello func"))
} |
|