gpt4 book ai didi

java - JNA是否释放Go CString返回值的内存

转载 作者:行者123 更新时间:2023-12-02 09:19:59 25 4
gpt4 key购买 nike

我有一个像这样的 JNA 接口(interface):


interface JJ {
String Hello(GoString.ByValue sql);
}

对应的Go原生代码:


//export Hello
func Hello(ss string) *C.char {

s := ss + " world"
return C.CString(s)
}

native 代码返回一个指向字符串的指针。

JNA 代码是否释放 native 代码分配的字符串指针?如果没有,如何释放它?

最佳答案

我将回答一般问题和具体示例。

JNA 不会维护对 native 内存的任何引用,除非您自己在 JNA 中分配它(例如,定义您传递的 byte[] 数组或 Memory 缓冲区)到一个函数)。在这些情况下,当 Java 对象被垃圾回收时, native 内存将被释放。

如果您没有将任何内存传递给 C 来填充,JNA 不会对 native 内存执行任何操作,并且您必须阅读 API 文档以了解释放 native 字符串的责任是什么。

C++ CString 类型不一定需要释放 unless it is stored in a new object 。但是,Go 确实将 CString 实现为对象,并记录了这些要求。对于您的特定示例,the docs说:

Memory allocations made by C code are not known to Go's memory manager. When you create a C string with C.CString (or any C memory allocation) you must remember to free the memory when you're done with it by calling C.free.

来自cgo wiki :

One important thing to remember is that C.CString() will allocate a new string of the appropriate length, and return it. That means the C string is not going to be garbage collected and it is up to you to free it. A standard way to do this follows.

// #include <stdlib.h>

import "C"
import "unsafe"
...
var cmsg *C.char = C.CString("hi")
defer C.free(unsafe.Pointer(cmsg))
// do something with the C string

Of course, you aren't required to use defer to call C.free(). You can free the C string whenever you like, but it is your responsibility to make sure it happens.

关于java - JNA是否释放Go CString返回值的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58759399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com