平台介绍
系统:ubuntu10.04
jdk:Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
gcc:gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5
如上一篇博客写道的先是简单的调用,本篇则是进一步带返回值的调用。
gcc编译器会根据文件后缀名来识别C或C++程序,所以既然是java调用C语言则C语言部分的文件的后缀名要以.c结尾,否则编译时容易出问题。
本示例中本地方法生命为静态方法,如果不是静态方法则过程略有差异,不详细描述。
JNI关于字符串处理部分API
jstring NewStringUTF(JNIEnv* env,const char bytes[])
const jbyte* GetStringUTFChars(JNIEnv*env,jstring string,jboolen* isCopy)
void ReleaseStringUTFChars(JNIEnv*env,jstring string,const jbyte bytes[])
1.编写java native方法并编译
- public class StringTest
- {
- public static native String sayHello(String strName);
- static
- {
- System.loadLibrary("StringTest");
- }
- }
public class StringTest
{
public static native String sayHello(String strName);
static
{
System.loadLibrary("StringTest");
}
}
java StringTest.java
2.用javah生成头文件
javah StringTest
3.编写C函数
- #include "StringTest.h"
- #include <stdio.h>
- #include <string.h>
- JNIEXPORT jstring JNICALL Java_StringTest_sayHello(JNIEnv * env, jclass cl, jstring instring)
- {
- jstring result;
- const char *str = (*env)->GetStringUTFChars(env, instring, JNI_FALSE);
- printf("Native methods---Hello,%s\n",str);
- char * res;
- strcpy(res,str);
- result=(*env)->NewStringUTF(env, res);
- (*env)->ReleaseStringUTFChars(env, instring,str);
- return result;
- }
#include "StringTest.h"
#include <stdio.h>
#include <string.h>
JNIEXPORT jstring JNICALL Java_StringTest_sayHello(JNIEnv * env, jclass cl, jstring instring)
{
jstring result;
const char *str = (*env)->GetStringUTFChars(env, instring, JNI_FALSE);
printf("Native methods---Hello,%s\n",str);
char * res;
strcpy(res,str);
result=(*env)->NewStringUTF(env, res);
(*env)->ReleaseStringUTFChars(env, instring,str);
return result;
}
4.编译c函数,生成lib文件
gcc -fPIC -I /usr/lib/jvm/java-6-sun/include/ -I /usr/lib/jvm/java-6-sun/include/linux/ -shared -o libStringTest.so StringTest.c
参数说明及易错部分提醒见上一篇日志
5.编写测试函数,编译并运行
- public class Demo
- {
- public static void main(String [] args)
- {
- String result = StringTest.sayHello("javaCallC");
- System.out.println("JavaMethod--"+result);
- }
- }
public class Demo
{
public static void main(String [] args)
{
String result = StringTest.sayHello("javaCallC");
System.out.println("JavaMethod--"+result);
}
}
编译:javac Demo.java
运行:java -Djava.library.path=. Demo(参数说明见上一篇博客)
6.程序结果
Native methods---Hello,javaCallC
JavaMethod--javaCallC