Java:
public class TestJNI
{
static
{
System.loadLibrary("TestJNI");
}
public native DiskInfo[] getStructArray();
public static void main(String[] args)
{
TestJNI jni = new TestJNI();
DiskInfo[] infos = jni.getStructArray();
for(int i = 0; i < infos.length; i++)
{
System.out.println(infos[i].name + " : " + infos[i].serialNo);
}
}
}
class DiskInfo
{
public String name;// 名称
public int serialNo;// 序列号
}
C++:
#include "TestJNI.h"
/*
typedef struct
{
char name[101];// 名称
int serialNo;// 序列号
} DiskInfo;
*/
JNIEXPORT jobjectArray JNICALL Java_TestJNI_getStructArray(JNIEnv *env, jobject jobj)
{
jobjectArray infos = NULL;// jobjectArray 为指针类型
jclass clsDiskInfo = NULL;// jclass 为指针类型
jobject obj;
jfieldID nameID;
jfieldID serialNoID;
jmethodID consID;
jsize len;
int i;
clsDiskInfo = env->FindClass("DiskInfo");
len = 5;
infos = env->NewObjectArray(len, clsDiskInfo, NULL);
nameID = env->GetFieldID(clsDiskInfo, "name", "Ljava/lang/String;");
serialNoID = env->GetFieldID(clsDiskInfo, "serialNo", "I");
consID = env->GetMethodID(clsDiskInfo, "", "()V");
for(i = 0; i < len; i++)
{
obj = env->NewObject(clsDiskInfo, consID);
env->SetObjectField(obj, nameID, env->NewStringUTF("disk"));
env->SetIntField(obj, serialNoID, (jint)i);
env->SetObjectArrayElement(infos, i, obj);
}
return infos;
}
/*
cl -I%java_inc% -I%java_inc%\win32 -LD TestJNI.cpp -FeTestJNI.dll
*/