jni记录
程序员文章站
2022-06-12 19:49:31
...
关于jni的简单使用
1.书写Java类
public class Lxy {
static {
System.loadLibrary("Lxy");
}
private native String sumLxy(int a, int b, String c);
public static void main(String[] args) {
int a = 10, b = 20;
String c = "name is lsd!", d = null;
d = new Lxy().sumLxy(a, b, c);
System.out.println("c的值为:" + c + " d的值为:" + d);
}
}
2.生成头文件
javac -h path 文件 例如:
javac -h . Lxy.java
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Lxy */
#ifndef _Included_Lxy
#define _Included_Lxy
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Lxy
* Method: sumLxy
* Signature: (IILjava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_Lxy_sumLxy
(JNIEnv *, jobject, jint, jint, jstring);
#ifdef __cplusplus
}
#endif
#endif
3.根据头文件时间声明
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Lxy.h"
#include <pthread.h>
JNIEXPORT jstring JNICALL Java_Lxy_sumLxy(JNIEnv *env, jobject jobj, jint a, jint b, jstring s)
{
jint c = a + b;
printf("c的值为:%d\n", c);
char *d = (*env)->GetStringUTFChars(env, s, NULL);
printf("%s\n", d);
jsize num = (*env)->GetStringLength(env, s);
printf("strlen = %d\n", num);
(*env)->ReleaseStringUTFChars(env, s, d);
char *str = (char *)malloc(sizeof(char) * 1000);
memset(str, 0, sizeof(char) * 1000);
strcpy(str, "alsjdnkasjndkjasndkljnaskjdnLKASDNKLJANsdAKSNDKLAsndjaNSD");
return (*env)->NewStringUTF(env, str);
}
4.编译C语言代码
gcc -fPIC -shared -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/linux" -o libLxy.so Lxy.c
5.运行
java -Djava.library.path=path Lxy
查看结果
[email protected]:~/project$ java -Djava.library.path=. Lxy
c的值为:30
name is lsd!
strlen = 12
c的值为:name is lsd! d的值为:alsjdnkasjndkjasndkljnaskjdnLKASDNKLJANsdAKSNDKLAsndjaNSD
[email protected]:~/project$
关于类型对照
// In "win\jni_mh.h" - machine header which is machine dependent
typedef long jint;
typedef __int64 jlong;
typedef signed char jbyte;
// In "jni.h"
typedef unsigned char jboolean;
typedef unsigned short jchar;
typedef short jshort;
typedef float jfloat;
typedef double jdouble;
typedef jint jsize;
更深入的内容后续更新…