内容简介:golang是类C的语言 支持调用C接口(不支持调用C++)Go调用C/C++的方式 :test.cpp和test.h是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 <stdio.h>
#include <stdlib.h>
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 <stdio.h>
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()
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 直观讲解-RPC调用和HTTP调用的区别
- 调用链系列一:解读UAVStack中的调用链技术
- 调用链系列二:解读UAVStack中的调用链技术
- 调用链系列三:解读UAVStack中的调用链技术
- dubbo源码解析(二十七)远程调用——injvm本地调用
- 微服务间的调用和应用内调用有什么区别
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Cyberwar
Kathleen Hall Jamieson / Oxford University Press / 2018-10-3 / USD 16.96
The question of how Donald Trump won the 2016 election looms over his presidency. In particular, were the 78,000 voters who gave him an Electoral College victory affected by the Russian trolls and hac......一起来看看 《Cyberwar》 这本书的介绍吧!