您的位置:首页 > 移动开发 > Android开发

Android的jni下c与java数据互传测试代码

2016-05-25 10:31 316 查看
test.java

public class test {
public native String test();
public native byte[] testbyte(byte[] by);
}
hello.c

#include <stdio.h>
#include <jni.h>
#include "com_example_jnitest_test.h"
#include <string.h>
#include <android/log.h>

#define LOG_TAG "jni_log"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)

JNIEXPORT jstring JNICALL Java_com_example_jnitest_test_test
(JNIEnv * env, jobject obj){
LOGI("------test-------");
return (*env)->NewStringUTF(env, "jni test 1234567890");
}

void printData(char *info, char *d, int len){
int i;
char buf[256];
for(i = 0; i < len; i++){
sprintf(buf+i*3, "%02x ", *d++);
}
LOGI("%s %s", info, buf);
}

JNIEXPORT jbyteArray JNICALL Java_com_example_jnitest_test_testbyte
(JNIEnv * env, jobject obj, jbyteArray jarrByte){
jsize len = (*env)->GetArrayLength(env, jarrByte);
LOGI("GetArrayLength = %d", len);
jbyte *b = (*env)->GetByteArrayElements(env, jarrByte, 0);
if(b == NULL){
LOGI("b is null");
return NULL;
}
printData("b data:", b, len);
char tmp[] ={0x11,0x12,0x13,0x14,0x15};
char buf[128];
memcpy(buf, b, len);
memcpy(buf+len, tmp, sizeof(tmp));
int size = len+sizeof(tmp);
jbyteArray ret = (*env)->NewByteArray(env, size);
(*env)->SetByteArrayRegion(env, ret, 0, size, buf);
(*env)->ReleaseByteArrayElements(env, ret, b, 0);
return ret;
}

MainActivity.java

public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
System.loadLibrary("Hello");
TextView tv = (TextView)rootView.findViewById(R.id.test);
test t = new test();
tv.setText(t.test());
Log.d("jni", "test");
byte[] by = {0x01,0x02,0x03};
byte[] out = t.testbyte(by);
Log.d("jni",b2h(out));
return rootView;
}
}
private static String b2h(byte[] in){
String ret = "";
for(int i = 0; i < in.length; i++){
String tmp = Integer.toHexString(in[i]&0xff);
if(tmp.length() == 1) tmp = "0" + tmp;
ret += tmp+" ";
}
return ret;
}


结果:

05-25 02:30:53.502: I/jni_log(330): ------test-------
05-25 02:30:53.502: D/jni(330): test
05-25 02:30:53.512: I/jni_log(330): GetArrayLength = 3
05-25 02:30:53.512: I/jni_log(330): b data: 01 02 03
05-25 02:30:53.512: W/dalvikvm(330): JNI: unpinPrimitiveArray(0x4054f888) failed to find entry (valid=1)
05-25 02:30:53.512: D/jni(330): 01 02 03 11 12 13 14 15
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: