1.MathOper.java文件:
class MathOper {
private native static void print();//在java中虽然print()是在c或c++中实现的,但是其调用的时候仍是通过声明所在类来调用的!它们实际上是属于当前类的!
private native static float sum(float a,float b);
public static void main(String args[])
{
// float res = new MathOper().sum(5, 1);//MathOper
// System.out.println("sum(5,1):"+res);
//
// new MathOper().print();
print();//这种调用方式需要将print()函数声明为static形式,从而不用new MathOper类
System.out.println("-------------------------\n");
float res = sum(8,9);
System.out.println("sum(5,1):"+res);
}
static
{
System.loadLibrary("MyMath");
}
}
javac MathOper.java
javah -jni MathOper生成MathOper.h头文件
2.创建c、c++动态链接库
引入jni.h头文件和lib(jvm.lib)所在目录
在Additional Dependencies中添加jvm.lib
将头文件和实现文件添加到项目中:
MathOper.h:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class MathOper */
#ifndef _Included_MathOper
#define _Included_MathOper
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: MathOper
* Method: print
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_MathOper_print
(JNIEnv *, jobject);
/*
* Class: MathOper
* Method: sum
* Signature: (FF)F
*/
JNIEXPORT jfloat JNICALL Java_MathOper_sum
(JNIEnv *, jobject, jfloat, jfloat);
#ifdef __cplusplus
}
#endif
#endif
MathOper.cpp:
#include <jni.h>
#include <stdio.h>
#include "MathOper.h"
/*
* Class: MathOper
* Method: print
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_MathOper_print
(JNIEnv *, jobject)
{
printf("hello world!\n");
return;
}
/*
* Class: MathOper
* Method: sum
* Signature: (FF)F
*/
JNIEXPORT jfloat JNICALL Java_MathOper_sum
(JNIEnv *, jobject, jfloat num1, jfloat num2)
{
return (num1+num2);
}
然后编译之,将生成的dll赋值到java的默认目录下即可
备注:在MathOper.java文件中如果有包文件时,如package com.test.Math;
用javah命令时会出现类似下面的错误:
C:\Users\callCpp\src>javac MathOper.java
C:\Users\callCpp\src>javah MathOper
错误: 找不到 'MathOper' 的类文件。
不知道什么原因,淡定。。。