@echooff rem
rem Root of Visual Developer Studio Common files. set VSCommonDir=D:msdev
rem
rem Root of Visual Developer Studio installed files.
rem set MSDevDir=D:msdevCommonmsdev98
rem
rem Root of Visual C++ installed files.
rem set MSVCDir=D:msdevVC98
rem
rem VcOsDir is used to help create either a Windows 95 or Windows NT specific path.
rem set VcOsDir=WIN95 if"%OS%"=="Windows_NT"set VcOsDir=WINNT
rem echo Setting environment for using Microsoft Visual C++ tools. rem if"%OS%"=="Windows_NT"setPATH=%MSDevDir%BIN;%MSVCDir%BIN;%VSCommonDir%TOOLS%VcOsDir%;%VSCommonDir%TOOLS;%MSVCDir%DEBUG;%VSCommonDir%OSSYSTEM;%PATH% if"%OS%"==""setPATH="%MSDevDir%BIN";"%MSVCDir%BIN";"%VSCommonDir%TOOLS%VcOsDir%";"%VSCommonDir%TOOLS";"%windir%SYSTEM";"%PATH%";%VSCommonDir%OSSYSTEM set INCLUDE=%MSVCDir%ATLINCLUDE;%MSVCDir%INCLUDE;%MSVCDir%MFCINCLUDE;%INCLUDE% set LIB=%MSVCDir%LIB;%MSVCDir%MFCLIB;%LIB%
rem set VcOsDir=
rem set VSCommonDir= rem modified by xionghe, antpath, classpath etc. setpath=%path%;d:/jakarta-ant/bin set JAGUAR_JDK13=d:/sharedjdk1.3.1_11 set JAGUAR_JDK14=d:/sharedjdk1.4.2_06 set JAGUAR_JDK15=d:/sharedjdk1.5.0_01 set JAVA_HOME=%JAGUAR_JDK14% setPATH=%JAVA_HOME%bin;%JAVA_HOME%/jre/bin;%PATH% set OLD_CLASSPATH=%CLASSPATH% set CLASSPATH=.;%JAVA_HOME%/lib/dt.jar;%JAVA_HOME%/lib/tools.jar;%JAVA_HOME%/jre/lib/rt.jar set CLASSPATH=%CLASSPATH%;%OLD_CLASSPATH%
set INCLUDE=%JAVA_HOME%/include;%JAVA_HOME%/include/win32;%INCLUDE%
/**
* Prompt Dll function entry */
JNIEXPORT jstring JNICALL Java_Prompt_getLine
(JNIEnv *env, jobject obj, jstring prompt) { char buf[128]; constchar*str; //char is just the jbyte str = (env)->GetStringUTFChars(prompt, NULL); if (str == NULL) { return NULL; /* OutOfMemoryError already thrown */
}
printf("%s", str);
(env)->ReleaseStringUTFChars(prompt, str); /* We assume here that the user does not type more than
* 127 characters */
scanf("%s", buf); return (env)->NewStringUTF(buf);
}
运行java -Djava.library.path=D:/msdev/MyProjects/helloworld Prompt,结果如下:
Type a line: fjkal
user typed: fjkal
注意,这里需要指定jvm的java.library.path值,表示load动态库时的搜索路径,或者你把生成的动态库拷贝到PATH路径中的任一目录里也可以,但不推荐这么做。
还要注意一点的是C++代码和C代码里env的调用形式不太一样。
C++: (env)->ReleaseStringUTFChars(prompt, str);
而C:(env*)->ReleaseStringUTFChars(env, prompt, str);
前边的实现里,必须作出jstring类型到char*的转换,并且适时的要释放内存,否则会出现内存泄漏。
这是一些比较简单的例子。后边会有适当的篇幅介绍jni以及jvm中一些比较复杂的应用。