c++代码转为go_Go调用C/C++

cgo

golang是类C的语言 支持调用C接口(不支持调用C++)

Go调用C/C++的方式 :

C : 直接调用C API

C++ : 通过实现一层封装的C接口来调用C++接口

Go集成C/C++的方式

go的源代码中直接声明C代码

比较简单的应用情况 可以直接使用这种方法 C代码直接写在go代码的注释中

注释之后紧跟import "C" 通过C.xx来引用C的结构和函数

package main

/*

#include

#include

typedef struct {

int id;

}ctx;

ctx *createCtx(int id) {

ctx *obj = (ctx *)malloc(sizeof(ctx));

obj->id = id;

return obj;

}

*/

import "C"

import (

"fmt"

"sync"

)

func main() {

var ctx *C.ctx = C.createCtx(100)

fmt.Printf("id : %d\n", ctx.id)

}

通过封装实现调用C++接口

目录结构 :C++代码放置在cpp目录下

C++代码需要提前编译成动态库(拷贝到系统库目录可以防止go找不到动态库路径),go程序运行时会去链接

.

├── cpp

│ ├── cwrap.cpp

│ ├── cwrap.h

│ ├── libgotest.dylib

│ ├── test.cpp

│ └── test.h

├── main.go

test.cpp和test.h是C++接口的实现

cwrap.h和cwrap.cpp是封装的C接口的实现

test.h

#ifndef __TEST_H__

#define __TEST_H__

#include

class Test {

public:

void call();

};

#endif

test.cpp

#include "test.h"

void Test::call() {

printf("call from c++ language\n");

}

cwrap.cpp

#include "cwrap.h"

#include "test.h"

void call() {

Test ctx;

ctx.call();

}

cwrap.h

#ifndef __CWRAP_H__

#define __CWRAP_H__

#ifdef __cplusplus

extern "C" {

#endif

void call();

#ifdef __cplusplus

}

#endif

#endif

main.go

package main

/*

#cgo CFLAGS: -Icpp

#cgo LDFLAGS: -lgotest

#include "cwrap.h"

*/

import "C"

func main() {

C.call()

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值