【发布时间】:2014-08-19 09:08:44
【问题描述】:
我正在开发基于 NDK 的 Android 应用程序。现在我正在学习使用示例“HelloWorld”应用程序。但它每次都会抛出错误。 请指教哪里错了?
P.S.:我所有的 cpp 文件都只在 jni 文件夹中。
在 LogCat 中,调试时显示;
08-19 14:52:59.340: W/dalvikvm(469): 找不到实现 本国的 Lcom/example/myfirstndkapp/MainActivity;.concateneMyStringWithCppString (Ljava/lang/String;)Ljava/lang/String;
这是基本代码:
MainActivity.java
package com.example.myfirstndkapp;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.*;
public class MainActivity extends ActionBarActivity {
static {
System.loadLibrary("MyFirstNDKApp");
}
private native String concateneMyStringWithCppString(String myString);
private EditText tvGetValue = null;
private TextView tvSetValue = null;
private Button btnCallCPPMethod = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
String str = concateneMyStringWithCppString("OutputString");
System.out.println("output : "+str);
}
}
Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := MyFirstNDKApp
LOCAL_SRC_FILES := CoreWrapper.cpp
LOCAL_SRC_FILES += Core.cpp
LOCAL_C_INCLUDES := $(LOCAL_PATH)
include $(BUILD_SHARED_LIBRARY)
Application.mk
APP_STL := gnustl_static
APP_ABI := all
Core.h 和 Core.cpp
//
// Core.h
#ifndef __MyFistNDKApp__Core__
#define __MyFistNDKApp__Core__
#include <iostream>
const char* concateneMyStringWithCppString(const char* myString);
#endif /* defined(__MyFistNDKApp__Core__) */
// Core.cpp
#include "Core.h"
const char* CPP_BASE_STRING = "cpp says hello world to %s";
const char* concateneMyStringWithCppString(const char* myString) {
char* concatenedString = new char[strlen(CPP_BASE_STRING) + strlen(myString)];
sprintf(concatenedString, CPP_BASE_STRING, myString);
return concatenedString;
}
CoreWrapper.c
// CoreWrapper.c
#include <string.h>
#include <jni.h>
#include "Core.h"
extern "C" {
JNIEXPORT jstring JNICALL com_example_myfirstndkapp_MainActivity_concateneMyStringWithCppString(JNIEnv* env, jobject thiz, jstring myString) {
return env->NewStringUTF(concateneMyStringWithCppString(env->GetStringUTFChars(myString, 0)));
}
}
但在运行时会引发错误:MainActivity.java 中的 concateneMyStringWithCppString 行甚至没有进入。它说一个无法识别的。这是错误日志:
在该方法内部调试时:它导航到 UnsatisfiedLinkError 类方法:
public UnsatisfiedLinkError(String detailMessage) {
super(detailMessage);
}
【问题讨论】:
-
是
javah生成的函数头还是手动输入的? -
一般来说,您应该从 hello-jni 示例开始,它在 NDK 中并且可以正常工作。在你让它工作后,你可以尝试改变它。
标签: java android c++ android-ndk java-native-interface