求助:一个关于Native中调用C++代码的问题“?
配置环境为android-ndk-r8e和sequoyah插件,在Eclipse中通过右键add Support Native添加动态库
在程序中实现一个简单的加法运算,这个加法通过调用C++ 代码实现,但是不成功,我调用C代码可以成功
在MainActivity.java中代码为
package com.example.ndkdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView displayLabel = (TextView)findViewById(R.id.display);
Button btn = (Button)findViewById(R.id.add_btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
double randomDouble =Math.random();
long x = Math.round(randomDouble*100);
randomDouble = Math.random();
long y = Math.round(randomDouble*100);
System.loadLibrary("NDKDemo");
long z= add(x,y);
String msg = x+"+"+y+"="+z;
displayLabel.setText(msg);
}
});
}
public native long add(long x,long y);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
在jni中由插件自动生成了一个NDKDemo.cpp和一个Android.mk我又添加了一个NDKDemo.h文件
在NDKDemo.cpp:
#include "NDKDemo.h"
jlong Java_com_example_ndkdemo_MainActivity_add( JNIEnv *env,jobject this,
jlong x,jlong y)
{
return x+y;
}
在NDKDemo.h:
#include <jni.h>
#ifndef NDKDEMO_H_
#define NDKDEMO_H_
extern "C"{
jlong Java_com_example_ndkdemo_MainActivity_add( JNIEnv* env,jobject this,jlong x,jlong y);
}
#endif
在Andriod.mk:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := NDKDemo
LOCAL_SRC_FILES := NDKDemo.cpp
include $(BUILD_SHARED_LIBRARY)
错误信息:
DescriptionResourcePathLocationType
expected ',' or '...' before 'this'NDKDemo.h/NDKDemo/jniline 7C/C++ Problem
'y' was not declared in this scopeNDKDemo.cpp/NDKDemo/jniline 7C/C++ Problem
make: *** [obj/local/armeabi/objs/NDKDemo/NDKDemo.o] Error 1NDKDemo C/C++ Problem
'x' was not declared in this scopeNDKDemo.cpp/NDKDemo/jniline 7C/C++ Problem
expected ',' or '...' before 'this'NDKDemo.cpp/NDKDemo/jniline 2C/C++ Problem
C++ Native?App
[解决办法]
你的Android.mk文件里面写的src文件有问题啊,要写成*.c文件不是*.cpp文件吧!
[解决办法]
#include <jni.h>
extern "C"{
JNIEXPORT jlong Java_com_example_hellojni_HelloJni_add(JNIEnv* env,jobject thiz,jlong x,jlong y);
}
#include "hello-jni.h"
JNIEXPORT jlong Java_com_example_hellojni_HelloJni_add( JNIEnv* env,jobject thiz,jlong x,jlong y)
{
return x+y;
}
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := hello-jni.cpp
include $(BUILD_SHARED_LIBRARY)