Android中java調用C的實現jniNDK

Android.mk代碼:

LOCAL_PATH := $(call my-dir)


include $(CLEAR_VARS)
LOCAL_LDLIBS    := -lm -llog 
LOCAL_MODULE    := myndk
LOCAL_SRC_FILES := myndk.c


include $(BUILD_SHARED_LIBRARY)

myndk.c代碼(獲取crc校驗):

#include <jni.h>
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <android/log.h>
#include <termios.h>
#include <unistd.h>
//#include <syspes.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <jni.h>
#include <errno.h>


//#include "devapi.h"
//#include "SerialPort.h"


#include "android/log.h"




static const char *TAG="serial_port";
#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)


typedef unsigned char INT8U ;
typedef unsigned short int INT16U ;
//extern "C"
JNIEXPORT jshort JNICALL Java_com_pda_ndktest_NDKtest_getcrc16
  (JNIEnv *env, jclass thiz, jshort len, jbyteArray array)
{
// cal_crc16_ext( 0xffff,p +1 ,idx -1)  ;
//
// INT16U cal_crc16_ext(INT16U initval ,INT8U *ptr,  INT16U len)
// {
// short crc;
// short i,j;
// char val;
// crc=0;
// crc= initval ;
//    for(i=0;i<len;i++)
//    {
// val =ptr[i];
//        crc^=val ;
//        for(j=0;j<8;j++)
//        {
//         if(crc&0x0001)
//               crc=(crc>>1)^0x8408;
//         else
//               crc=(crc>>1);
//        }
//    }
// return(crc);
// }
//short cal_crc16_ext(byte[]ptr,  short len) //for RD5112 protocol


// short crc = 0;
// short i,j;
// char val;
// crc=0;
// crc= 0xffff ;
//    for(i=0;i<len;i++)
//    {
// val =datas[i];
//        crc^=val ;
//        for(j=0;j<8;j++)
//        {
//         if(crc&0x0001)
//               crc=(crc>>1)^0x8408;
//         else
//               crc=(crc>>1);
//        }
//    }
// return(crc);


// INT16U cal_crc16_ext(INT16U initval ,INT8U *ptr,  INT16U len) //for RD5112 protocol
// {
// 07FFF00100
char buf[128];
jbyte *jby = (*env)->GetByteArrayElements(env, array, 0);
    memcpy(buf, jby, len);
    (*env)->ReleaseByteArrayElements(env, array, jby, 0);
    LOGE("len(len = %x)",len);
INT16U crc;
INT16U i,j;
INT8U val;
crc=0;
crc= 0xffff ;
   for(i=0;i<len;i++)
   {
    LOGE("crc(crc = %x)",crc);






val = buf[i];
LOGE("val(val = %x)",val);
//        crc^=val ;//這行代碼錯誤
crc = crc^val;
       for(j=0;j<8;j++)
       {
        if(crc&0x0001)
              crc=(crc>>1)^0x8408;
        else
              crc=(crc>>1);
       }
   }
   LOGE("crc(crc = %x)",crc);
return(crc);
// }


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章