数值参数与返回值
当在c和java之间传递数字时,应该知道他们彼此对应的类型
例如: c 也有 int 和long数据类型,但是他们的实现却是取决于平台的,在一些平台上,int 类型是32位的整数,基于这个原因,java本地接口定义了jint ,jlong 等类型
java编程语言 c语言 字节
boolean jboolean 1
byte jbyte 1
char jchar 2
short jshort 2
int jint 4
long jlong 8
float jfloat 4
double jdouble 8
在jni.h 中 ,还定义了常量 JNI_FALSE = 0 和 JNI_TRUE = 1。
用 printf 格式化字数字
Printf1.java
class Printf1{
public static native int print(int width,int precision,double x);
static{
System.loadLibrary("Printf1");
}
}
注意,用c 实现该方法时,所有的int 和double 都转换成了 jint 和jdouble
Printf1.c
#include "Printf1.h"
#include <stdio.h>
JNIEXPORT jint JNICALL Java_Printf1_print (JNIEnv* env, jclass cl, jint width, jint precision , jdouble x){
char fmt[30];
jint ret;
sprintf(fmt,"%%%d.%df",width,precision);
ret = printf(fmt,x);
fflush(stdout);
return ret;
}
当在c和java之间传递数字时,应该知道他们彼此对应的类型
例如: c 也有 int 和long数据类型,但是他们的实现却是取决于平台的,在一些平台上,int 类型是32位的整数,基于这个原因,java本地接口定义了jint ,jlong 等类型
java编程语言 c语言 字节
boolean jboolean 1
byte jbyte 1
char jchar 2
short jshort 2
int jint 4
long jlong 8
float jfloat 4
double jdouble 8
在jni.h 中 ,还定义了常量 JNI_FALSE = 0 和 JNI_TRUE = 1。
用 printf 格式化字数字
Printf1.java
class Printf1{
public static native int print(int width,int precision,double x);
static{
System.loadLibrary("Printf1");
}
}
注意,用c 实现该方法时,所有的int 和double 都转换成了 jint 和jdouble
Printf1.c
#include "Printf1.h"
#include <stdio.h>
JNIEXPORT jint JNICALL Java_Printf1_print (JNIEnv* env, jclass cl, jint width, jint precision , jdouble x){
char fmt[30];
jint ret;
sprintf(fmt,"%%%d.%df",width,precision);
ret = printf(fmt,x);
fflush(stdout);
return ret;
}