golang使用Cgo调用C++动态库 |
您所在的位置:网站首页 › golang调用接口 › golang使用Cgo调用C++动态库 |
背景
因项目需要,最近在研究如何Golang如何调用C++动态库,目前网上有两种主流的方式,一种是使用swig,一种是使用C封装一层C++接口,本文主要介绍第二种方式。 接口封装test.h C++头文件 // test.h #ifndef TEST_H #define TEST_H #include class Test { public: void sayHello(); }; #endiftest.cpp sayHello函数实现 #include"test.h" void Test::sayHello(){ printf("hello world\n"); }api.h 接口头文件 #pragma once #ifdef __cplusplus extern "C" { #endif void sayHelloWorld(); #ifdef __cplusplus } #endifapi.cpp 接口头文件实现 // test.cpp #include "test.h" #include "api.h" void sayHelloWorld(){ Test ts; ts.sayHello(); } 生成动态库 gcc -fpic -shared test.cpp api.cpp -o libapi.so golang代码编写为了方便起见,将api.h,test.h,libapi.so放在同一目录下 注意:-lstdc++必须要加到引用的动态库代码片之后,否则在linux编译时会报undefined reference to `sayHelloWorld’ 错误 linux下编译在当前目录下使用,go build命令,golang会自动寻找动态库进行连接 go build运行结果 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |