gpt4 book ai didi

java - 将 jstring 从 jni c 代码发送到接收字符串作为参数的 java 函数

转载 作者:搜寻专家 更新时间:2023-10-31 20:21:59 24 4
gpt4 key购买 nike

如何将 JNI C 代码中的 jstring 发送到接收 StringJava 函数争论?

我已经阅读了有关 callVoidMethodA(....) 的功能,但它们不接受任何东西,例如 jstring

最佳答案

您没有提到目标类名和目标方法签名。因此,考虑一下,例如 java.lang.StringBuilder.append(java.lang.String)方法。

// First lets assume you have already received the next variables
void foo( JNIEnv* env, jobject obj )
{
// Call StringBuilder.append() method
}

现在您需要类名和方法签名(根据 docs )

static char const StringBuilder_ClassName = "java/lang/StringBuilder";
static char const StringBuilder_append_MethodName = "append";
static char const StringBuilder_append_MethodSignature =
"(Ljava/lang/String;)Ljava/lang/StringBuilder;";

要从 JNI 代码调用 java 方法,您应该获取 jmethodID

static jclass StringBuilder_Class = 0;
static jmethodID StringBuilder_append_Method = 0;

void Init( JNIEnv* env )
{
if( StringBuilder_Class == 0 ) {
StringBuilder_Class = (*env)->FindClass( env, StringBuilder_ClassName );
// TODO: Handle error if class not found
}
if( StringBuilder_append_Method == 0 ) {
StringBuilder_append_Method = (*env)->GetMethodID( env, StringBuilder_Class,
StringBuilder_append_MethodName, StringBuilder_append_MethodSignature );
// TODO: Handle error if method not found
}
}

void foo( JNIEnv* env, jobject obj )
{
Init();
char* str;
// str = ...;
jstring jString = (*env)->NewStringUTF( env, str );
// Because StringBuild.append() returns object, you should call CallObjectMethod
jobject ret = (*env)->CallObjectMethod( env, obj, jString );
// Here you can release local references, i.e.
// (*env)->DeleteLocalRef( env, ret );
// (*env)->DeleteLocalRef( env, jString );
// But it is not necessary. Local references are released automatically when
// thread returns from JNI code to Java code.
// So you can ignore the returned value and not to release the jString local
// reference, i.e. just call
// (*env)->CallObjectMethod( env, obj, jString );
}

关于java - 将 jstring 从 jni c 代码发送到接收字符串作为参数的 java 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12872742/

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