日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

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

發布時間:2023/12/19 c/c++ 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()

}

總結

以上是生活随笔為你收集整理的c++代码转为go_Go调用C/C++的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。