jni 学习笔记(java调用c++)

来源:互联网 发布:关于单片机的论文 编辑:程序博客网 时间:2024/05/29 09:48

package com.native;

public class MyNative {


public native static void set( int num );
public native static int get();

}

javac 指令

javac G:\Job\android\wrok\Native\src\com\native

javah 指令

set classpath=G:\Job\android\wrok\Native\src

javah -jni com.native.MyNative

 生成.dll文件

用vs创建一个win32 项目进入win32应用程序向导界面 点击下一步选择应用程序类型:dll 点击完成,

将生成的.h(com_native_MyNative)文件copy到创建的vs项目中,新建一个.cpp(MyNative.cpp)文件将com_native_MyNative.h中的方法实现最后编译项目生成项目.dll文件。

package com.native;

public class Main {
public static void main( String args[] ){
System.loadLibrary( "MyNative" );
com.native.MyNative a = new com.native.MyNative();
int i = 99;
a.set(i);
System.out.println( "set value: " + i );
System.out.println( "get value: " + a.get() );
}
}


com_native_MyNative.h

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


#ifndef _Included_com_native_MyNative
#define _Included_com_native_MyNative
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_native_MyNative
 * Method:    set
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_com_native_MyNative_set
  (JNIEnv *, jclass, jint);


/*
 * Class:     com_native_MyNative
 * Method:    get
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_com_native_MyNative_get
  (JNIEnv *, jclass);


#ifdef __cplusplus
}
#endif
#endif



MyNative.cpp

#include"com_native_MyNative.h"
int i;
JNIEXPORT void JNICALL Java_com_native_MyNative_set
  (JNIEnv *, jclass, jint j)
{
i = j;
printf("set ok!\n");
}


JNIEXPORT jint JNICALL Java_com_native_MyNative_get
  (JNIEnv *, jclass)
{
printf( "java 调用C++" );
return i;
}