Android------- jni返回结构体

1.创建工程,添加jni

Android------- jni返回结构体_第1张图片


2. main.cpp

#include 

struct test_data
{
	char name[256];
	int  num;
	double average;
};

 extern "C" {
     JNIEXPORT jobject  JNICALL Java_com_re_struct_MainActivity_call(JNIEnv * env, jobject obj, jobject classobj);
 };

 JNIEXPORT jobject  JNICALL Java_com_re_struct_MainActivity_call(JNIEnv * env, jobject obj, jobject classobj)
 {
	 jclass objectClass = env->FindClass("com/re/struct/test_data");

	 jfieldID name = env->GetFieldID(objectClass, "name", "Ljava/lang/String;");
	 jfieldID num = env->GetFieldID(objectClass, "num", "I");
	 jfieldID average = env->GetFieldID(objectClass, "average", "D");

	 env->SetObjectField(classobj, name, env->NewStringUTF("hello world"));
	 env->SetIntField(classobj, num, 10);
	 env->SetDoubleField(classobj, average, 2.5);
	 return classobj;
 }

3. test_data.java

package com.re.struct;


public class test_data {
	public String name;
	public int  num;
	public double average;
}

4. MainActivity.java

package com.re.struct;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {
	
	static{
		System.loadLibrary("main");
	}

	private native test_data call(test_data data);
	private test_data data = new test_data();
	private static final String TAG="######";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		data = call(data);
		Log.e(TAG, "name:" + data.name);
		Log.e(TAG, "num:" + data.num);
		Log.e(TAG, "average:" + data.average);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

5. 效果:

Android------- jni返回结构体_第2张图片


6. 补充:

Java类型

符号
boolean

byte

char

C  
short
int
long L  
float F  

double

D  

void

objects对象 Lfully-qualified-class-name;        L类名;
Arrays数组 [array-type [数组类型 
methods方法                  (argument-types)return-type(参数类型)返回类型

你可能感兴趣的:(android)