cgo的效率 golang_如何在golang的cgo中使用std :: vector或其他容器?

由于Go的垃圾回收效率不高,作者尝试使用cgo结合C/C++来分配大量内存并用std::vector存储对象。然而,在cgo中直接引用std::vector导致编译错误。解决方案是将C++代码放入单独的.cpp文件,并声明为C链接。在Go文件中提供函数原型,并使用`go build`或`go run package`代替`go run foo.go`来编译多个文件。
摘要由CSDN通过智能技术生成

I want to malloc large number of objects in to memory.(about 100 million objects) because the gc of golang is not effective enough,so i need to use c/c++ to malloc memory and use std::vector to hold objects.

this is my code,i want use std container in cgo:

package main

import (

"fmt"

)

/*

#include

#include

#include

#include

using namespace std;

void dosome(){

vector ivec; // empty vector

for (vector::size_type ix = 0; ix != 10; ++ix)

ivec[ix] = ix; // disaster: ivec has no elements

}

*/

// #cgo LDFLAGS: -lstdc++

import "C"

//import "fmt"

func main() {

C.dosome()

var input string

fmt.Scanln(&input)

}

and have error message below:

go run stddemo.go

# command-line-arguments

./stddemo.go:13:10: fatal error: 'vector' file not found

#include

^

1 error generated.

how can i set the include path or is there another idea?

解决方案

While you can use C++ with CGo, you can't embed that code inside the .go file, since it ultimately gets built with a C compiler.

Instead, place your dosome function in a separate .cpp file in the same directory as the .go file, and declare your function to use C linkage. For example:

extern "C" {

void dosome() {

vector ivec;

...

}

}

If you include a prototype for the function in the CGo comment in the .go file so you can call it from Go.

Since you have multiple files now, you can't use the go run foo.go shorthand any more (since it only compiles a single file). Instead, you will need to use go run package or go build package, where your code is located at $GOPATH/src/package.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值