登录
首页 >  Golang >  Go问答

处理返回 CString 时的内存泄漏问题

来源:stackoverflow

时间:2024-02-13 12:36:23 393浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《处理返回 CString 时的内存泄漏问题》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我有以下函数签名,然后返回 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 ctypes
from time import sleep
library = 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_p

for 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 ctypes
from time import sleep
library = ctypes.cdll('./stackoverflow.so')
get_data = library.getdata
free_me = library.freeme
free_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 getdata
func getdata(symbol, day, month, year *c.char) *c.char {
  combine := "combine"
  log.println(string(combine))
  return c.cstring(string(combine))
}

//export freeme
func freeme(data *c.char) {
  c.free(unsafe.pointer(data))
}

func main() {}

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

python3 --version
python 3.8.10 
go version
go version go1.19.2 linux/amd64
go build -o stackoverflow.so -buildmode=c-shared github.com/sjeandeaux/stackoverflow
python3 stackoverflow.py 
2023/01/03 13:54:14 combine
b'combine'                                                                                                                                  
...
from ubuntu:18.04

run apt-get update -y && apt-get install python -y

copy stackoverflow.so stackoverflow.so
copy stackoverflow.py stackoverflow.py

cmd ["python", "stackoverflow.py"]
docker build --tag stackoverflow .
docker run -ti stackoverflow
2023/01/03 15:04:24 combine
b'combine'
...

到这里,我们也就讲完了《处理返回 CString 时的内存泄漏问题》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>