基本步骤和在java中调用C语言方法一样,只列出主要代码。
MyTest.java
public class MyTest{ private native String[] getInfo(); static { System.loadLibrary("MyTest"); } public static void main(String[] args){ while(true){ MyTest test=new MyTest(); String[] str=test.getInfo(); System.out.println("getInfo:"+str[0]); } } }
生成的MyTest.h头文件:
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class MyTest */ #ifndef _Included_MyTest #define _Included_MyTest #ifdef __cplusplus extern "C" { #endif /* * Class: MyTest * Method: getInfo * Signature: ()[Ljava/lang/String; */ JNIEXPORT jobjectArray JNICALL Java_MyTest_getInfo (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif
#include <stdio.h> #include<sys/types.h> #include<fcntl.h> #include<termios.h> #include "MyTest.h" #define BAUDRATE B38400 #define MODEMDEVICE "/dev/ttyS0" JNIEXPORT jobjectArray JNICALL Java_MyTest_getInfo (JNIEnv *env, jclass cls){ int fd,c=0,res; struct termios oldtio,newtio; char buf[256]; printf("start ...\n"); fd=open(MODEMDEVICE,O_RDWR | O_NOCTTY); if(fd<0) { perror(MODEMDEVICE); exit(1); } printf("open...\n"); tcgetattr(fd,&oldtio); bzero(&newtio,sizeof(newtio)); newtio.c_cflag=BAUDRATE | CS8 | CLOCAL | CREAD; newtio.c_iflag=IGNPAR; newtio.c_oflag=0; newtio.c_lflag=ICANON; tcflush(fd,TCIFLUSH); tcsetattr(fd,TCSANOW,&newtio); printf("reading...\n"); res=read(fd,buf,255); buf[res]=0; printf("res=%d vuf=%s\n",res,buf); printf("close...\n"); close(fd); tcsetattr(fd,TCSANOW,&oldtio); jstring str; jobjectArray args = 0; args=(*env)->NewObjectArray(env,1,(*env)->FindClass(env,"java/lang/String"),0); str = (*env)->NewStringUTF(env,buf); (*env)->SetObjectArrayElement(env,args,0,str); return args; }
libMyTest.so:MyTest.o makefile gcc -Wall -rdynamic -shared -o libMyTest.so MyTest.o MyTest.o:MyTest.c MyTest.h gcc -Wall -c MyTest.c -I./ -I/usr/lib/jvm/java-7-openjdk-i386/include -I/usr/lib/jvm/java-7-openjdk-i386/include/linux cl: rm -rf *.o *.so
(-----------完------------)