[使用cgo从Go返回字符串]

问题描述 投票:0回答:1

我必须使用golang调用Java函数。我正在使用cgoJNA进行此操作。

golang例程唯一要做的就是分配内存并返回char**。从Java方面,我正在使用char**中提到的String[]接收documentation

下面是C helper和golang函数的详细信息:

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(0)
    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
/usr/local/bin/idea

导致错误的原因是什么,如何解决?还有其他方法可以使用[]stringgolang返回JNA吗?

java go jna cgo
1个回答
0
投票

您写:

func getSearchKeysA() **C.char {
    set_char := C.cmalloc(0)
    defer C.free(unsafe.Pointer(set_char))
    C.setElement(set_char, C.CString("hello world"), C.int(0))
    return set_char
}

将执行为:

func getSearchKeysA() **C.char {
    set_char := C.cmalloc(0)
    C.setElement(set_char, C.CString("hello world"), C.int(0))
    C.free(unsafe.Pointer(set_char))
    return set_char
}

set_char之后是指free吗?


The Go Programming Language Specification版本7月31日,2019

Defer statements

“ defer”语句调用一个函数,该函数的执行被推迟到周围函数返回的那一刻,要么是因为周围的函数执行了一个return语句,到达了结尾其功能主体,或者因为对应的goroutine是惊慌。

© www.soinside.com 2019 - 2024. All rights reserved.