一>TestNative.java
public class TestNative{
public native int sayHello(int a,int b);
public static void main(String args[]){
System.loadLibrary("JNI");
TestNative tst=new TestNative();
int a=tst.sayHello(20,30);
System.out.println(a);
}
}
一>javac TestNative.java
一>javah -jni TestNative ---生成TestNative.h
TestNative.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class TestNative */
#ifndef _Included_TestNative
#define _Included_TestNative
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: TestNative
* Method: sayHello
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_TestNative_sayHello
(JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
一>//JNI.cpp:c++文件,文件名一定要与System.loadLibrary("JNI")里的相同;
#include "TestNative.h"
#include <iostream>
using namespace std;
JNIEXPORT jint JNICALL Java_TestNative_sayHello
(JNIEnv *, jobject, jint x, jint y)
{
int a;
a=x+y;
printf("hello") //如果是cout<<"123"<< 运行后输出:1236,出错.
return a;
}
一>运行
把.dll放到 system32下,或放到bin,或和java文件放一起
输出:
hello
50
******************************已测试成功
备注:
A 其中的jni.h,jni_md.h通常在 jdk/include/ 可以先拷贝到VC安装目录下的include目录下.一劳永逸,
以后可以方便使用JNI技术.
B 全部的数据类型需要考虑Java和VC的接口问题.用jint jstring 等.
C 函数名称和自动生成的.h文件中规定的一致.命名规则是: Java_使用类_方法名
1535

被折叠的 条评论
为什么被折叠?



