普通网友 2018-09-03 21:41
浏览 838
已采纳

如何通过CGO从C函数中的内部void *返回[] byte?

I am wrapping an C function with the following definition:

int parser_shift(parser* parser, void* buffer, int length);

It removes up to length bytes from internal buffer of unparsed bytes, storing them in the given buffer.

Now I wish to wrap it into a Go function with the following definition:

func (p *Parser) Shift() []byte {
    var buffer []byte
    // TODO:

    return buffer
}

What is the right way of writing to finish the TODO in above with CGO?

I tried the following way, however it crashed with error: Error in "/path/to/my/program': free(): invalid next size (fast): 0x00007f8fe0000aa0:

var buffer []byte
bufStr := C.CString(string(buffer))
defer C.free(unsafe.Pointer(bufStr))
C.parser_shift(p.Cparser, unsafe.Pointer(bufStr), C.int(8192))
buffer = []byte(C.GoString(bufStr))
return buffer
  • 写回答

1条回答 默认 最新

  • duanjing4623 2018-09-04 05:58
    关注

    Assuming that your parser_shift function returns the number of bytes actually stored in the buffer, you can do something like this:

    func (p *Parser) Shift() []byte {
        var buffer [8192]byte
        parsed := int(C.parser_shift(p.Cparser, unsafe.Pointer(&buffer[0]), C.int(len(buffer))))
        return buffer[:parsed]
    }
    

    There is no need to convert to or from string, just pass it the memory that you want it to write to.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题