如题,最近fix历史的坑— JNI DETECTED ERROR IN APPLICATION: GetStringUTFChars received NULL jstring 的case 然后很自信的根据如下信息去排查代码,结果做了几个小时的无用功。
A/k.myapplicatio: java_vm_ext.cc:545] JNI DETECTED ERROR IN APPLICATION: GetStringUTFChars received NULL jstring
java_vm_ext.cc:545] in call to GetStringUTFChars
java_vm_ext.cc:545] from void com.sdk.myapplication.MainActivity.triggerGetStringUTFCharsNPE(java.lang.String, java.lang.String)
原因上面的出现信息中, from 某个Jni的方法是指JVM调到该方法后GetStringUTFChars入参jstring为空的情况,必不是特指该方法体中调GetStringUTFChars的地方出现了NULl指针,而是包括该方法中调用其它的C/C++方法出现NULL指针的情况。所以我们去定位这类问题,还是要细仔看个崩溃堆栈,才能快速定位到是那个地方产出的NULL指针,避免无效输出 如上示例是根据自己的业务代码,抽像出来的 示例代码如下 java
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
triggerGetStringUTFCharsNPE("hello", null);//故意传一个null
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
public native void triggerGetStringUTFCharsNPE(String p1, String p2);
}
jni
#include <jni.h>
#include <string>
#include <android/log.h>
static const char* TAG = "Demo";
void nestFunction(JNIEnv *env, jstring p2) {
//这里p1简单通过参数传进来,但实际业务逻辑中可能是通过其它方法/方式获取到的
const char* pStr = env->GetStringUTFChars(p2, nullptr);
__android_log_print(ANDROID_LOG_DEBUG, TAG, "pStr:%s", pStr);
env->ReleaseStringUTFChars(p2, pStr);
}
extern "C" JNIEXPORT jstring JNICALL
Java_com_sdk_myapplication_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}extern "C"
JNIEXPORT void JNICALL
Java_com_sdk_myapplication_MainActivity_triggerGetStringUTFCharsNPE(JNIEnv *env, jobject thiz,
jstring p1, jstring p2) {
const char* pStr1 = env->GetStringUTFChars(p1, nullptr);
__android_log_print(ANDROID_LOG_DEBUG, TAG, "pStr1:%s", pStr1);
env->ReleaseStringUTFChars(p1, pStr1);
//故意让nestFunction产生 JNI DETECTED ERROR IN APPLICATION: GetStringUTFChars received NULL jstring
nestFunction(env, p2);
}
|