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

我想将大量对象 malloc 到内存中。(大约 1 亿个对象)因为 golang 的 gc 不够有效,所以我需要使用 c/c++ 来 malloc 内存并使用 std::vector 来保存对象。这是我的代码,我想在 cgo 中使用 std 容器:


package main


import (

    "fmt"

)


/*

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <vector>



using namespace std;


void dosome(){

    vector<int> ivec;   // empty vector

    for (vector<int>::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)

}

并有以下错误消息:


go run stddemo.go 

# command-line-arguments

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

#include <vector>

     ^

1 error generated.

我如何设置包含路径或者还有其他想法?


HUX布斯
浏览 207回答 3
3回答

萧十郎

虽然您可以将 C++ 与 CGo 一起使用,但您不能将该代码嵌入到.go文件中,因为它最终是使用 C 编译器构建的。相反,将您的dosome函数放在.cpp与该.go文件相同的目录中的单独文件中,并声明您的函数使用 C 链接。例如:extern "C" {&nbsp; &nbsp; void dosome() {&nbsp; &nbsp; &nbsp; &nbsp; vector<int> ivec;&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; }}如果在.go文件的 CGo 注释中包含函数的原型,则可以从 Go 调用它。由于您现在有多个文件,您不能再使用go run foo.go速记(因为它只编译一个文件)。相反,您需要使用go run package或go build package,您的代码位于$GOPATH/src/package。

慕森王

呃,我觉得你的结论有点太快了。GC 成本由两件事驱动:程序产生的垃圾越多,GC 运行的次数就越多。第二:要扫描的指针越多,单个 GC 花费的时间就越长。也就是说:只要你把你的 1 亿个东西放到一个 go slice 中并把它们放在那里:GC 就不必运行太多,因为没有垃圾。第二:如果你的东西不包含指针,GC 时间,如果它仍然发生,就可以了。所以,我的问题是:你的东西有指针吗?

犯罪嫌疑人X

如果您只想调用某人的 golang 代码,这是一种快速且效率低下的方法:package mainimport "C"import "fmt"import "unsafe"func intArrayFromC (src unsafe.Pointer, sz int) []uint64 {&nbsp; &nbsp; dest := make([]uint64, sz)&nbsp; &nbsp; copy(dest, (*(*[1000000000]uint64)(unsafe.Pointer(src)))[:sz:sz])// big number dose not affect ram.&nbsp; &nbsp; return dest}//export doPrintfunc doPrint(src unsafe.Pointer, sz int){&nbsp; &nbsp; var numbers []uint64 = intArrayFromC(src, sz);&nbsp; &nbsp; for i := 0; i < len(numbers); i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%d&nbsp; index: %d\n", numbers[i], i)&nbsp; &nbsp; }}func main() {}和 C++ 代码:#include "print.h"#include <string.h>#include <vector>int main() {&nbsp; &nbsp; std::vector<GoUint64> numbers{99,44,11,00,2,33,44};&nbsp; &nbsp; while (1) {&nbsp; &nbsp; &nbsp; &nbsp; doPrint(numbers.data(), numbers.size());&nbsp; &nbsp; }&nbsp; &nbsp; return 0;}
打开App,查看更多内容
随时随地看视频慕课网APP