golang的cgo支持调用C++的方法

sohoer2003 · · 20201 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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

 


有疑问加站长微信联系(非本文作者)

本文来自:博客园

感谢作者:sohoer2003

查看原文:golang的cgo支持调用C++的方法

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

20201 次点击  
加入收藏 微博
1 回复  |  直到 2019-01-23 20:58:10
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传