Android ndk windows下使用环境设置与编程实例:由.java自动生成xxx.h

来源:互联网 发布:小学生题目解答软件 编辑:程序博客网 时间:2024/04/29 18:30

思路:

    本文从java到c 自动生成jni的xx.h文件
在eclipse中创建好xx.java文件,然后编译在相应的bin目录下生成xx.class文件,要生成xx.h的jni头文件就需要这个.class文件,
使用javah command 格式如下:javah -jni -classpath xxx.class
注意路径指定到.class文件的包文件夹的上一层,例如要编译bin\classes\com\example\hellojni\HelloJni.class 文件,
需要cd 到classes\下就可
然后执行命令:
javah -jni -classpath . com.example.hellojni.HelloJni
会在classes\ 生成com_example_hellojni_HelloJni.h 文件
 
Ps: 有个‘.’在 -classpath 命令后。

code 如下:HelloJni.java

package com.example.hellojni;

import android.app.Activity;
import android.widget.TextView;
import android.os.Bundle;


public class HelloJni extends Activity
{
 TextView  tv ;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

         tv = new TextView(this);
          tv.setText( "get string from c: " + printHexString( getByteArray("2341")) );
        setContentView(tv);  
              
    }    

    public native String  stringFromJNI();    
    public native String[] getStringArray();
    public native byte[] getByteArray(String userPin);
    
  
    static {  
        System.loadLibrary("hello-jni");
    }
    
 }

编译后自动生成HelloJni.h,

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_hellojni_HelloJni */

#ifndef _Included_com_example_hellojni_HelloJni
#define _Included_com_example_hellojni_HelloJni
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_example_hellojni_HelloJni
 * Method:    stringFromJNI
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI
  (JNIEnv *, jobject);

/*
 * Class:     com_example_hellojni_HelloJni
 * Method:    getStringArray
 * Signature: ()[Ljava/lang/String;
 */
JNIEXPORT jobjectArray JNICALL Java_com_example_hellojni_HelloJni_getStringArray
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

然后在.cpp中实现具体的函数功能:

#include <com_example_hellojni_HelloJni.h>
#include <stdio.h>
#include <string.h>

JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI
  (JNIEnv *env, jobject thiz)
{
 return (*env)->NewStringUTF(env,"the log of android is mad");
}

JNIEXPORT jbyteArray JNICALL Java_com_example_hellojni_HelloJni_getByteArray
(JNIEnv *env, jobject thiz, jstring jstr)
{
 char const *bStr = NULL;
 // jstring 2 char*
 bStr = (*env)->GetStringUTFChars(env,jstr, 0);
 jbyteArray RtnArr = NULL;
 RtnArr = (*env)->NewByteArray(env,strlen(bStr));
 (*env)->SetByteArrayRegion(env,RtnArr, 0, strlen(bStr), (jbyte*)bStr);

// if(bStr)
// {
//  free(bStr);
// }

 return RtnArr;

}

完成之后就可以编译了。

0 0
原创粉丝点击