c调用java函数返回值,通过JNI从C ++调用Java函数返回一个字符串

本文指导了如何通过JNI在C++中调用Java类MyClass的getValue方法,并获取其中String变量的值。重点在于正确使用GetMethodID和CallObjectMethod函数,以及处理可能的JNI错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Suppose I have a Java class like this :

class MyClass

{

String value = "a string value";

String getValue()

{

return value;

}

}

I've been trying for hours to implement a JNI function that calls a Java function and returns a string.

Could someone show me through a snippet how to call the "getValue" function from a C++ using JNI and obtain a jstring variable with the value of String variable from "MyClass.

// C++

jobject result;

jMethodID method_getValue = m_env->GetMethodID(native_object,"getValue","()Ljava/lang/String;");

result = m_env->CallObjectMethod(native_object, method_getValue);

解决方案

jMethodID method_getValue = m_env->GetMethodID(native_object,"getValue","()Ljava/lang/String;");

here, native_object is supposed to be the class definition object (jclass) of MyClass

jmethodID GetMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig);

whereas to here:

result = m_env->CallObjectMethod(native_object, method_getValue);

NativeType CallMethod(JNIEnv *env, jobject obj,

jmethodID methodID, ...);

Your CallObjectMethod expects as first parameter an object from MyClass, no jclass.

http://download.oracle.com/javase/1.4.2/docs/guide/jni/spec/functions.html

so either one of the calls is wrong here...

probably the getMethodID... you should definitely check for NULL there.

cheers,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值