如何在golang的cgo中使用std :: vector或其他容器? [英] how to use std::vector or other container in cgo of golang?

查看:1257
本文介绍了如何在golang的cgo中使用std :: vector或其他容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  package main 

导入(
fmt


/ *
#include< stdio.h>
#include< stdlib.h>
#include< string.h>
#include< vector>


使用namespace std;

void dosome(){
vector< int> IVEC; (vector< int> :: size_type ix = 0; ix!= 10; ++ ix)
ivec [ix] = ix; //灾难:ivec没有元素
}

* /
// #cgo LDFLAGS:-lstdc ++
导入C

//输入fmt
func main(){

C.dosome()

var输入字符串
fmt.Scanln(&输入)
}

并在下面显示错误消息:

  go run stddemo.go 
#命令行参数
./stddemo.go:13:10:致命错误:'vector '找不到文件
#include< vector>
^
1产生的错误。

如何设定包含路径或是否有其他想法?
虽然你可以在C ++中使用C ++,但是你不能在 .go 文件中嵌入代码,因为它最终用C编译器构建。



相反,将 dosome 函数放在一个单独的 .cpp 文件放在与 .go 文件相同的目录中,并声明您的函数使用C链接。例如:

  externC{
void dosome(){
vector< int> IVEC;
...
}
}

如果包含在 .go 文件中的CGo注释中为函数创建原型,以便您可以从Go中调用它。



从你现在有多个文件,你不能再使用 go run foo.go 速记(因为它只编译一个文件)。相反,您需要使用 go run package go build package ,您的代码位于 $ GOPATH / src / package


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 <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)
}

and have error message below:

go run stddemo.go 
# command-line-arguments
./stddemo.go:13:10: fatal error: 'vector' file not found
#include <vector>
     ^
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<int> 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.

这篇关于如何在golang的cgo中使用std :: vector或其他容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆