Go:返回 CString 时如何处理内存泄漏?

go:返回 cstring 时如何处理内存泄漏?

php小编西瓜在这里为大家分享关于Go语言中处理返回CString时的内存泄漏问题的解决方法。在Go语言中,C字符串是以null结尾的字节数组,而Go语言的字符串是以长度为前缀的字节数组。当我们需要将Go字符串转换为C字符串并返回时,需要注意内存的分配和释放,以避免内存泄漏问题的发生。本文将介绍几种处理内存泄漏的方法,帮助大家解决这个常见的问题。

问题内容

我有以下函数签名,然后返回 json 字符串

func getdata(symbol, day, month, year *c.char) *c.char {  combine, _ := json.marshal(combinerecords)  log.println(string(combine))  return c.cstring(string(combine))}

登录后复制

然后在 python 中调用 go 代码

import ctypesfrom time import sleeplibrary = ctypes.cdll.LoadLibrary('./deribit.so')get_data = library.getData# Make python convert its values to C representation.# get_data.argtypes = [ctypes.c_char_p, ctypes.c_char_p,ctypes.c_char_p,ctypes.c_char_p]get_data.restype = ctypes.c_char_pfor i in range(1,100):    j= get_data("BTC".encode("utf-8"), "5".encode("utf-8"), "JAN".encode("utf-8"), "23".encode("utf-8"))    # j= get_data(b"BTC", b"3", b"JAN", b"23")    print('prnting in Python')    # print(j)    sleep(1)

登录后复制

它在 python 端工作得很好,但我担心当在 python 端循环调用该函数时会出现内存泄漏。

如何处理内存泄漏?我应该返回 bytes 而不是 cstring 并在 python 端处理字节以避免内存泄漏吗?我确实找到了这个链接来处理它,但不知何故我不知道编组后返回的 json 字符串的大小

解决方法

python 应该如下所示:

import ctypesfrom time import sleeplibrary = ctypes.cdll('./stackoverflow.so')get_data = library.getdatafree_me = library.freemefree_me.argtypes = [ctypes.pointer(ctypes.c_char)]get_data.restype = ctypes.pointer(ctypes.c_char)for i in range(1,100):  j = get_data("", "", "")  print(ctypes.c_char_p.from_buffer(j).value)  free_me(j)  sleep(1)

登录后复制

go 应该是这样的:

package main/*#include */import "c"import (  "log"  "unsafe")//export getdatafunc getdata(symbol, day, month, year *c.char) *c.char {  combine := "combine"  log.println(string(combine))  return c.cstring(string(combine))}//export freemefunc freeme(data *c.char) {  c.free(unsafe.pointer(data))}func main() {}

登录后复制

并使用此命令行生成共享库:

python3 --versionpython 3.8.10 go versiongo version go1.19.2 linux/amd64go build -o stackoverflow.so -buildmode=c-shared github.com/sjeandeaux/stackoverflowpython3 stackoverflow.py 2023/01/03 13:54:14 combineb'combine'                                                                                                                                  ...

登录后复制

from ubuntu:18.04run apt-get update -y && apt-get install python -ycopy stackoverflow.so stackoverflow.socopy stackoverflow.py stackoverflow.pycmd ["python", "stackoverflow.py"]

登录后复制

docker build --tag stackoverflow .docker run -ti stackoverflow2023/01/03 15:04:24 combineb'combine'...

登录后复制

以上就是Go:返回 CString 时如何处理内存泄漏?的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2483624.html

(0)
上一篇 2025年3月4日 21:21:32
下一篇 2025年2月18日 03:40:21

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论