golang使用Cgo调用C++动态库

您所在的位置:网站首页 golang调用接口 golang使用Cgo调用C++动态库

golang使用Cgo调用C++动态库

2023-08-16 10:12| 来源: 网络整理| 查看: 265

背景

因项目需要,最近在研究如何Golang如何调用C++动态库,目前网上有两种主流的方式,一种是使用swig,一种是使用C封装一层C++接口,本文主要介绍第二种方式。

接口封装

test.h C++头文件

// test.h #ifndef TEST_H #define TEST_H #include class Test { public: void sayHello(); }; #endif

test.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 } #endif

api.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放在同一目录下 在这里插入图片描述 main.go

package main // #cgo LDFLAGS: -L . -lapi -lstdc++ // #cgo CFLAGS: -I ./ // #include "api.h" import "C" func main() { C.sayHelloWorld() }

注意:-lstdc++必须要加到引用的动态库代码片之后,否则在linux编译时会报undefined reference to `sayHelloWorld’ 错误

linux下编译

在当前目录下使用,go build命令,golang会自动寻找动态库进行连接

go build

在这里插入图片描述

./testForWebAis

运行结果 在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3