Go: How to handle memory leaks when returning a CString?
php editor Xigua is here to share with you the solution to the memory leak problem when returning CString in the Go language. In Go, C strings are null-terminated byte arrays, while Go strings are length-prefixed byte arrays. When we need to convert a Go string to a C string and back, we need to pay attention to the allocation and release of memory to avoid memory leaks. This article will introduce several methods to deal with memory leaks to help you solve this common problem.
Question content
I have the following function signature, which then returns a json string
func getdata(symbol, day, month, year *c.char) *c.char { combine, _ := json.marshal(combinerecords) log.println(string(combine)) return c.cstring(string(combine)) }
Then call the go code in python
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)
It works fine on the python side, but I'm worried about a memory leak when calling the function in a loop on the python side.
How to deal with memory leaks? Should I return bytes
instead of cstring
and handle the bytes on the python side to avoid memory leaks? I did find this link to handle it but somehow I don't know the size of the json string returned after marshalling
Workaround
python should look like this:
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 should look like this:
package main /* #include <stdlib.h> */ 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() {}
And use this command line to generate the shared library:
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' ...
The above is the detailed content of Go: How to handle memory leaks when returning a CString?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

Yes, H5 page production is an important implementation method for front-end development, involving core technologies such as HTML, CSS and JavaScript. Developers build dynamic and powerful H5 pages by cleverly combining these technologies, such as using the <canvas> tag to draw graphics or using JavaScript to control interaction behavior.

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

The method of customizing resize symbols in CSS is unified with background colors. In daily development, we often encounter situations where we need to customize user interface details, such as adjusting...

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

Regarding the reasons and solutions for misaligned display of inline-block elements. When writing web page layout, we often encounter some seemingly strange display problems. Compare...

Interfaces and polymorphism in Go: Clarifying common misunderstandings Many Go beginners often connect the concepts of "duck type" and "polymorphism" with Go...
