Go调用C/C++

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

cgo

golang是类C的语言 支持调用C接口(不支持调用C++)
Go调用C/C++的方式 :

  1. C : 直接调用C API
  2. C++ : 通过实现一层封装的C接口来调用C++接口

Go集成C/C++的方式

  1. 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)
}
  1. 通过封装实现调用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接口的实现

  1. test.h
#ifndef __TEST_H__
#define __TEST_H__

#include <stdio.h>

class Test {
public:
    void call();
};

#endif
  1. test.cpp
#include "test.h"

void Test::call() {
    printf("call from c++ language\n");
}
  1. cwrap.cpp
#include "cwrap.h"
#include "test.h"

void call() {
    Test ctx;
    ctx.call();
}
  1. cwrap.h
#ifndef __CWRAP_H__
#define __CWRAP_H__

#ifdef __cplusplus
extern "C" {
#endif
void call();

#ifdef __cplusplus
}
#endif

#endif
  1. main.go
package main

/*
#cgo CFLAGS: -Icpp

#cgo LDFLAGS: -lgotest

#include "cwrap.h"
*/
import "C"

func main() {
    C.call()
}

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

本文来自:简书

感谢作者:sakura3zz

查看原文:Go调用C/C++

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

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