分享

golang调用c++文件

 9252娃儿 2017-01-13
??

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`)

 目录结构: 

 
|-project
|  |-lib
|  |  |-libhello.so
|  |-include
|  |  |-hello.h
|  |-src
|  |  |-main.go
|  |-pkg
|  |-bin
 

 

编译为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")) } 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多