• golang调用c++文件


    简要步骤:

    1,将c++ 的方法提取到头文件.h中( )

    2,编译cc(c++)文件为动态链接库so文件  gcc -fPIC -shared hello.c -o libhello.so 

    3,将头文件放入include目录 .so放入lib目录

    4,go程序中指定 CFLAGS 和 LDFLAGS

    #cgo  CFLAGS:  -I  ./include 
    #cgo  LDFLAGS:  -L .b  -lhello   -Wl,-rpath,/usr/localb  

    5,运行(go 程序的时候)发布时候指定 export LD_LIBRARY_PATH="lib文件所在目录" (`pwd`)

    export LD_LIBRARY_PATH=./lib

     目录结构: 

    |-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
    ", __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 ", __FUNCTION__, __LINE__, str); }
    */ import "C" func main() { C.hello(C.CString("call C hello func")) }

    参考文章:golang的cgo支持调用C++的方法

    golang之cgo---调用C/C++动态库函数

    http://doumadou.github.io/golangdiao-yong-ccfang-fa.html  (需要步骤五才能运行成功) 

    附件:下载

     

  • 相关阅读:
    团队里A和B吵架了,经理M该干啥?
    一个程序员的哲学思考(关于编程、关于人生)
    程序员在大学里究竟应该学习什么?
    如何检查自己是否平庸?
    关于如何读代码?
    老说技术更迭快,可十年到底可以淘汰多少知识?
    现代软件工程里的困惑
    略谈各国企业的差异
    Silverlight4Beta之操作摄像头/麦克风
    Silverlight4Beta之Binding新特性(下)
  • 原文地址:https://www.cnblogs.com/lavin/p/golang-call-cpp-or-cc-file.html
Copyright © 2020-2023  润新知