我必须从 Java 调用 Go 函数。我正在使用cgo和JNA这样做。
Go 例程唯一要做的就是分配内存并返回一个char**. 从 Java 方面,我收到了文档中提到的char**使用。String[]
以下是 C 助手和 Go 函数的详细信息:
static char** cmalloc(int size) {
return (char**) malloc(size * sizeof(char*));
}
static void setElement(char **a, char *s, int index) {
a[index] = s;
}
//export getSearchKeysA
func getSearchKeysA() **C.char {
set_char := C.cmalloc(1)
defer C.free(unsafe.Pointer(set_char))
C.setElement(set_char, C.CString("hello world"), C.int(0))
return set_char
}
Java方面:
String[] getSearchKeysA();
我得到的错误是:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007fff6b15323e, pid=92979, tid=0x0000000000000c07
#
# JRE version: Java(TM) SE Runtime Environment (8.0_192-b12) (build 1.8.0_192-b12)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.192-b12 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# C [libsystem_kernel.dylib+0x723e] __pthread_kill+0xa
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /Users/dfb3/datafabric/pocs/go-java-connector/hs_err_pid92979.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
我注意到的是,当 malloc 分配内存时会出现问题。
我已经尝试过从方法中ulimit -c unlimited
删除和删除defer C.free(unsafe.Pointer(set_char))
。
错误的原因可能是什么,我该如何解决?有没有其他方法可以[]string
从 Go 中返回 a 使用JNA
?
由于错字和基于@PeterSO 的答案而更新:
我最初写的是 malloc(0) 但它应该是 malloc(1)
func C.CString(string) *C.char
,它应该为我分配内存,不是吗?
DIEA
哈士奇WWW
相关分类