dsn1327 2018-01-29 09:19
浏览 74
已采纳

外部功能:谁释放内存?

I'm calling a Go function from Python. Go function returns a string, specifically, a GoString with the string itself being allocated on Go's side.

Question

Who's responsible for deallocation of this memory?


A very simplified example follows.

Go side:

func Create(optsEncoded string) (res string, serr string) {
    opts := map[string]interface{}{}
    if err := json.Unmarshal([]byte(optsEncoded), &opts); err != nil {
        return "", errWithStack(err)
    }
    options := translateCreateOptions(opts)

    result := ...

    payload, err := json.Marshal(result)
    if err != nil {
        return "", errWithStack(err)
    }
    return string(payload), ""
}

Cython bindings:

cpdef object py_create(object items, bytes options):
    cdef GoString opts = ...
    cdef bytes message

    cdef Create_return result = Create(opts)

    if result.r0.n == 0:
        message = result.r1.p
        raise Exception("Something happened")
    message = result.r0.p
    # Do I need to deallocate result.r0 and result.r1?
    return message.decode("utf-8")
  • 写回答

1条回答 默认 最新

  • drj58429 2018-01-29 10:27
    关注

    I don't think you should return a GoString to C. Since the memory of GoString is managed by the go runtime and will be garbage collected. It's unreliable in C land to use this string. What you should do is return a CString by calling cs := C.CString(s). Memory allocations made by C code are not known to Go's memory manager. So I think its up to you to mange which side to free the CString, here and here.

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料