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

背景

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

接口封装

test.h C++头文件

// test.h
#ifndef TEST_H
#define TEST_H
#include<stdio.h>

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

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

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值