我想将大量的对象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)
}
Run Code Online (Sandbox Code Playgroud)
并在下面有错误消息:
go run stddemo.go
# command-line-arguments
./stddemo.go:13:10: fatal error: 'vector' file not found
#include <vector>
^
1 error generated.
Run Code Online (Sandbox Code Playgroud)
我如何设置包含路径还是有其他想法?
虽然您可以将C++与CGo一起使用,但您无法将该代码嵌入到.go文件中,因为它最终是使用C编译器构建的.
而是将dosome函数放在与.cpp文件相同的目录中的单独文件中.go,并声明您的函数使用C链接.例如:
extern "C" {
void dosome() {
vector<int> ivec;
...
}
}
Run Code Online (Sandbox Code Playgroud)
如果在.go文件中的CGo注释中包含该函数的原型,则可以从Go调用它.
由于您现在有多个文件,因此不能再使用go run foo.go速记(因为它只编译单个文件).相反,您需要使用go run package或go build package代码所在的位置$GOPATH/src/package.