当我运行Android应用程序时,我遇到了一个错误,我使用了JNI函数和c代码.当它运行时,我得到以下消息:@H_404_2@
@H_404_2@
Fatal signal 11 (SIGSEGV) at 0xe480001d (code=1),thread 5465@H_404_2@
@H_404_2@
JNIEXPORT jstring JNICALL Java_ir_bassir_ndktest4_MainActivity_getName
(JNIEnv *env,jobject obj){
jclass cls = (*env)->GetObjectClass(env,obj);
jmethodID mid = (*env)->GetStaticMethodID(env,cls,"testJava","([Ljava/lang/String)[Ljava/lang/String");
jstring plainText = (*env)->NewStringUTF(env,"Hello from JNI ! Compiled with ABI 2222 ");
jstring result = (*env)->CallStaticObjectMethod(env,mid,plainText);
return (*env)->NewStringUTF(env,plainText);
}
而在Java方面:@H_404_2@
@H_404_2@
public class MainActivity extends ActionBarActivity {
public native String getName();
public static String testJava(String txt){
Log.d("BP","call back to java method");
String result = txt + "its added in JAVA";
return result;
}
static{
System.loadLibrary("HelloJNI");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String name = getName();
Log.d("BP",name);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button,so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
最佳答案
这段代码的JNI方面是C,而不是C,而C指针处理的较宽松处理是问题的一部分.您的代码在这两行中断:@H_404_2@
原文链接:https://www.f2er.com/android/431267.html@H_404_2@
jstring plainText = (*env)->NewStringUTF(env,"Hello from JNI ! Compiled with ABI 2222 ");
return (*env)->NewStringUTF(env,plainText);
因为NewStringUTF有签名@H_404_2@
@H_404_2@
jstring NewStringUTF(JNIEnv *env,const char *bytes);
这意味着这个电话被打破了:@H_404_2@
@H_404_2@
// vvvvvvvvv--- plainText is not of the right type!
(*env)->NewStringUTF(env,plainText)
C编译器接受它,因为jstring是一个指针类型(C编译器不会),所以plainText将被解释为char const *,它继续做傻事.@H_404_2@
无论如何,我怀疑你是想说的@H_404_2@
@H_404_2@
return result;
…但是如果你打算返回plainText,那就说吧@H_404_2@
@H_404_2@
return plainText;
没有必要复制.