1

I am up with implementing my Java Native Interface functions in Golang using the golang C lib.
Now I want to convert a jstring to an UTF-8 string using the JNI function GetStringUTFChars but I get an error when doing it. These are the steps I have done:

In my Java class (called MyClass) where I have defined the JNI method, I have:

public static native void print(String msg);

Using javah, I have generated the .h-file with the function defined in C language:

JNIEXPORT void JNICALL Java_com_mypackage_MyClass_print
  (JNIEnv *, jclass, jstring);

Then, in my Go code I have the following code:

package main

// #cgo CFLAGS: -I/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/include
// #cgo CFLAGS: -I/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/include/darwin
/*
#include <jni.h>
*/
import "C"

//export Java_com_mypackage_MyClass_print
func Java_com_mypackage_MyClass_print(env *C.JNIEnv, clazz C.jclass, str C.jstring) {

    _ = C.GetStringUTFChars(env, str, 0)

}

When I build the go file using:
go build -buildmode=c-shared -o libmyclass.dylib libmyclass.go
then I get the following error:

could not determine kind of name for C.GetStringUTFChars

How should I call the GetStringUTFChars defined in the JNI spec so I then can print the string with fmt.println?

EDIT 2
Removed "edit 1" since the procedure above was correct, it was just the LD_LIBRARY_PATH variable that was not set.

4

1 回答 1

1

JNI 之类的函数GetStringUTFChars是函数指针,不能直接从 Go 中调用。您必须将所需的函数包装在单独的 C 文件中。例如

jx.c

#include <jni.h>

const char* jx_GetStringUTFChars(JNIEnv *env, jstring str, jboolean *isCopy) {
    return (*env)->GetStringUTFChars(env, str, isCopy);
}

从 C 文件创建库后,您的 Go 文件将如下所示:

package main

/*
#cgo CFLAGS: -I/usr/java/jdk1.8.0_162/include/ -I/usr/java/jdk1.8.0_162/include/linux/
#cgo LDFLAGS: -L${SRCDIR}/ -ljx

#include "jx.h"
*/
import "C"
import (
    "fmt"
)

//export Java_com_mypackage_MyClass_print
func Java_com_mypackage_MyClass_print(env *C.JNIEnv, clazz C.jclass, str C.jstring) {
    s := C.jx_GetStringUTFChars(env, str, (*C.jboolean)(nil))
    fmt.Println(C.GoString(s))
}

func main() {}

包装函数有一个单独的 C 文件的原因是因为文档中的这个子句:

在文件中使用 //export 会限制前导码:因为它被复制到两个不同的 C 输出文件中,所以它不能包含任何定义,只能包含声明。

于 2018-11-12T15:31:53.833 回答