使用jni实现在Java中调用C++的方法

来源:互联网 发布:虚拟机安装linux系统 编辑:程序博客网 时间:2024/06/05 21:50

在前面的博客中介绍的都是c语言调用java的方法或者是java调用c语言的方法,这篇博客将介绍在java中调用c++的方法

实现方式(部分步骤有所省略,详细步骤请参考前面的博客)

第一步:在eclipse下创建一个Android工程,并且修改activity_main.xml中的代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="调用c++的本地方法"         android:onClick="click"/></RelativeLayout>


第二步:修改MainActivity.java中的代码

package com.fyt.helloJni5;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.View;import android.widget.Toast;public class MainActivity extends Activity {static {//加载打包生成的so类库System.loadLibrary("hello");}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}//调用c++本地方法的按钮响应函数public void click(View view) {Toast.makeText(this, helloCpp(), Toast.LENGTH_SHORT).show();}//定义一个本地方法,方法体使用c++语言实现public native String helloCpp();}

第三步:在jni目录下新建一个com.fyt.helloJni5.MainActivity.h文件,com.fyt.helloJni5.MainActivity.h文件中添加下面的代码(com.fyt.helloJni5.MainActivity.h文件是使用javah命令生成的,关于javah命令的使用可以参考我的博客)

/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class com_fyt_helloJni5_MainActivity */#ifndef _Included_com_fyt_helloJni5_MainActivity#define _Included_com_fyt_helloJni5_MainActivity#ifdef __cplusplusextern "C" {#endif/* * Class:     com_fyt_helloJni5_MainActivity * Method:    helloCpp * Signature: ()Ljava/lang/String; */JNIEXPORT jstring JNICALL Java_com_fyt_helloJni5_MainActivity_helloCpp  (JNIEnv *, jobject);#ifdef __cplusplus}#endif#endif

第四步:在jni目录下的hello.cpp文件中添加下面的代码

#include <jni.h>#include "com.fyt.helloJni5.MainActivity.h"JNIEXPORT jstring JNICALL Java_com_fyt_helloJni5_MainActivity_helloCpp  (JNIEnv* env, jobject object){ char* str = "hello world jni !";    //把c++语言的字符串转换成java的字符串    jstring jstr = env->NewStringUTF(str);    return jstr;}

最后一步:打包运行,执行成功后点击按钮会弹出吐司对话框,吐司对话框上会显示c++语言中的字符串



0 0
原创粉丝点击