2018-09-03 21:41
浏览 581

如何通过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

图片转代码服务由CSDN问答提供 功能建议


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



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

正确的方法是什么 与CGO一起完成上述TODO的想法?

我尝试了以下方法,但是由于以下错误而崩溃:“ / path / to / my / program'中的错误:free():无效的下一个大小(快速):0x00007f8fe0000aa0:< / p>

  var缓冲区[] 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))
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题