python - 外部函数 : who deallocates memory?

标签 python go memory-management cython

我正在从 Python 调用 Go 函数。 Go 函数返回一个字符串,具体来说,是一个 GoString,字符串本身是在 Go 端分配的。

问题

谁负责释放此内存?


下面是一个非常简化的示例。

走一边:

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 绑定(bind):

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

最佳答案

我认为你不应该将 GoString 返回给 C。因为 GoString 的内存由 go 运行时管理,并且将被垃圾收集。在 C 地使用这个字符串是不可靠的。您应该做的是通过调用 cs := C.CString(s) 返回一个 CString。 Go 的内存管理器不知道由 C 代码进行的内存分配。所以我认为由您来决定释放 CStringhere 的哪一方和 here .

关于python - 外部函数 : who deallocates memory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48497879/

相关文章:

linux - 进程的显卡内存和虚拟地址空间

c++ - 如何防止并行代码耗尽所有可用的系统内存?

python - 如何从类外部向类方法添加属性?

python - 为什么Python的时间函数(如perf_counter_ns)解析会不一致?

python:如何比较一个列表中的元素

go - 无法将 txdb 与 Gormigrate 一起使用

security - 通过不安全的网络轻松安全地连接(两个端点都完全受控)

java - 什么时候是释放 Java 缓存对象的好时机?

python - 冒泡排序查询

testing - 当测试文件在模块中时,如何运行 `go test`?