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.

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

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan