1 import java.io.PrintWriter;
2 public class Printf {
3 public static native void fprint(PrintWriter out,String format,double x);
4 static {
5 System.loadLibrary(\"Printf\");
6 }
7 }
2) 实现本地方法的C语言代码:
1 #include \"Printf.h\"
2 #include <stdlib.h>
3 #include <string.h>
4 #include <float.h>
5
6 JNIEXPORT void JNICALL Java_Printf_fprint
7 (JNIEnv* env, jclass cl, jobject out, jstring format, jdouble x)
8 {
9 const char* cformat = env->GetStringUTFChars(format,NULL);
10 char* cstr = (char*)calloc(strlen(cformat) + 20,sizeof(char));
11 sprintf(cstr,cformat,x);
12 jstring str = env->NewStringUTF(cstr);
13 free(cstr);
14 env->ReleaseStringUTFChars(format,cformat);
15
16 jclass class_PrintWriter = env->GetObjectClass(out);
17 //对应于void PrintWrite.print(String)方法
18 jmethodID id_print = env->GetMethodID(class_PrintWriter,\"print\",\"(Ljava/lang/String;)V\");
19 //这里Void是CallXxxMethod一组方法中的一个,表示调用函数的返回值类型。
20 //因此该方法的返回值也是void,如果调用CallIntMethod,其返回值将为jint。
21 env->CallVoidMethod(out,id_print,str);
22 }
3) 含有main函数的调用测试代码:
1 import java.io.PrintWriter;
2 public class MyTest {
3 public static void main(String[] args) throws Exception {
4 double price = 44.95;
5 double tax = 7.75;
6 double amountDue = price