这是一个比较麻烦的方法。。
一、首先,你要先安装一个VC,我的装在了D:\software\C++\Microsoft Visual Studio
二、我的jdk安装目录是D:\Program Files\Java\jdk1.7.0_67,
那么把:
D:\Program Files\Java\jdk1.7.0_67\include 下面的 jni.h 和
D:\Program Files\Java\jdk1.7.0_67\include\win32 下面的 jni_md.h
复制到 D:\ruanjian\C++\Microsoft Visual Studio\VC98\Include
三、在f:\新建一个Sample.java
public class Sample
{
public native int intMethod(int n);
public native boolean booleanMethod(boolean bool);
public native String stringMethod(String text);
public native int intArrayMethod(int[] args);
public static void main(String[] args)
{
System.loadLibrary("Sample");
Sample sample = new Sample();
int square = sample.intMethod(5);
boolean bool = sample.booleanMethod(true);
String text = sample.stringMethod("JAVA");
int sum = sample.intArrayMethod(new int[] { 1, 1, 2, 3, 5, 8, 13 });
System.out.println("intMethod: " + square);
System.out.println("booleanMethod: " + bool);
System.out.println("stringMethod: " + text);
System.out.println("intArrayMethod: " + sum);
}
}
四、在cmd下输入命令:
f:
javac Sample.java
javah -classpath . Sample
结果在同一目录下生成了 Sample.class 和 Sample.h
(在别人的电脑下javah Sample就可以生成 Sample.h,不明白为什么我的不可以……)
五、在f:\再新建一个Sample.c
#include "Sample.h"
#include
JNIEXPORT jint JNICALL Java_Sample_intMethod(JNIEnv *env, jobject obj, jint num)
{
return num * num;
}
JNIEXPORT jboolean JNICALL Java_Sample_booleanMethod(JNIEnv *env, jobject obj, jboolean boolean)
{
return !boolean;
}
JNIEXPORT jstring JNICALL Java_Sample_stringMethod(JNIEnv *env, jobject obj, jstring string)
{
const char *str = (*env)->GetStringUTFChars(env, string, 0);
char cap[128];
strcpy(cap, str);
(*env)->ReleaseStringUTFChars(env, string, str);
return (*env)->NewStringUTF(env, strupr(cap));
}
JNIEXPORT jint JNICALL Java_Sample_intArrayMethod(JNIEnv *env, jobject obj, jintArray array)
{
int i, sum = 0;
jsize len = (*env)->GetArrayLength(env,array);
jint *body = (*env)->GetIntArrayElements(env, array, 0);
for (i=0; i
{
sum += body[i];
}
(*env)->ReleaseIntArrayElements(env, array, body, 0);
return sum;
}
void main(){}
六、cmd下输入:
SET PATH=D:\software\C++\Microsoft Visual Studio\VC98\Bin;%PATH%
SET INCLUDE=D:\software\C++\Microsoft Visual Studio\VC98\Include;%INCLUDE%
SET LIB=D:\software\C++\Microsoft Visual Studio\VC98\Lib;%LIB%
cl -LD Sample.c -FeSample.dll
java Sample
效果:
PS:若使用c1命令时出现找不到mspdb60.dll时,可上网去载一个,
若电脑是32位系统放到 C:\Windows\System32,64位放到C:Windows\SysWOW64下,然后"开始-运行-regsvr32 mspdb60.dll"