戈朗
import "C"
//export MyFunction
func MyFunction(str *C.char) *C.char {
goStr := C.GoString(str)
msg := goStr + " world"
return C.CString(msg)
}
func main() {}
爪哇岛
public interface MyLib extends Library {
MyLib INSTANCE = Native.load("mylib.so", MyLib.class);
String MyFunction(String str);
}
public class CGoExample {
public static void main(String[] args) {
String str = "Hello";
String msg = MyLib.INSTANCE.MyFunction(str);
System.out.println(msg);
}
}
此代码有效,Java 字符串传递给 Go,Go 返回新字符串。我遇到的问题是,Go 返回的 CString 不会被 Java 或 Go 垃圾回收器解除分配。CGO文档指出“调用方有责任安排释放它,例如通过调用C.free”,当然,在我的情况下,调用C.free将不起作用,因为我返回CString,如果我在返回CString之前释放CString,我不会从Go函数中获得正确的响应。我也尝试过调用,但我发现在返回语句之前将调用延迟语句的困难方式。defer C.free(unsafe.Pointer(msg))
由于我需要返回CString,我假设它的内存需要从java中释放,我该怎么做?
编辑:
根据DanielWiddis的评论,我尝试了以下内容,但java进程存在于代码-1073741819。
// #include <stdlib.h>
import "C"
import "unsafe"
//export MyFunction
func MyFunction(str *C.char) *C.char {
goStr := C.GoString(str)
msg := goStr + " world"
return C.CString(msg)
}
//export Free
func Free(str *C.char){
C.free(unsafe.Pointer(str))
}
func main() {}
public interface MyLib extends Library {
MyLib INSTANCE = Native.load("mylib.so", MyLib.class);
String MyFunction(String str);
void Free(String str);
}
public class CGoExample {
public static void main(String[] args) {
String str = "Hello";
String msg = MyLib.INSTANCE.MyFunction(str);
System.out.println(msg);
MyLib.INSTANCE.Free(msg);
}
}
慕桂英4014372
肥皂起泡泡
相关分类