您的位置:首页 > 编程语言 > C语言/C++

cgo调用C++函数实现

2017-08-22 16:50 323 查看
转载地址:http://www.cnblogs.com/sohoer2003/p/4329085.html

大概的流程为:

1)将C++中的某个函数转换成C的形式,变成端口的形式暴露出去

2)将声明放在.h文件中,将函数体封装在动态库或者静态库中,供go调用

3)在go中通过cgo LDFLAGS指明Lib所在的地址,通过cgo CFLAGS指令include所在的地址,即可调用

在这里我走了一些弯路,供参考:

1)忽略#cgo LDFLAGS #cgo CFLAGS以为是被注释的部门,其实很重要

2)c.h文件中忽视#ifdef __cplusplus该指令指明内部使用c++的方式进行编译

3)忽略test.go文件中编译制导指令 -lstdc++ 很关键

1)swift,貌似官网的推荐
2)extern "C"
我使用后者,用起来比较爽,上代码
c.h

1 #pragma once
2
3 #ifdef __cplusplus
4 extern "C" {
5 #endif
6 void test();
7 #ifdef __cplusplus
8 }
9 #endif


 
c.c

1 #include "cplus.hpp"
2 #include "c.h"
3
4 void test() {
5     A *a = new B();
6     a->test();
7 }


 
cplus.hpp

1 #pragma once
2
3 class A {
4     public:
5         virtual void test();
6 };
7 class B: public A {
8     public:
9         void test();
10 };


cplus.cpp

#include <iostream>
#include "cplus.hpp"

using namespace std;

void A::test() {
cout << "a" << endl;
}

void B::test() {
cout << "b" << endl;
}


build.sh

1 g++ -o cplus.o -c cplus.cpp
2 g++ -o c.o -c c.c
3 ar r libc_test.so c.o cplus.o


test.go

1 package main
2 // #cgo LDFLAGS: -L . -lc_test -lstdc++
3 // #cgo CFLAGS: -I ./
4 // #include "c.h"
5 import "C"
6
7 func main(){
8
9     C.test()
10
11 }


执行顺序

1 ./build.sh
2 go build test.go
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: