jni 从c传递map到java_如何通过JNI将HashMap从Java发送到C.

您的问题的答案实际上归结为为什么您想要将Map传递给C而不是在Java中迭代Map并将内容传递给C.但是,我是谁来质疑为什么?

您问如何访问HashMap(在您提供的代码中,Map)字段?在Java中为它编写一个访问器方法,并在传递容器Object时从C调用该访问器方法.下面是一些简单的示例代码,展示了如何将Map从Java传递到C,以及如何访问Map的size()方法.从中,您应该能够推断出如何调用其他方法.

容器对象:

public class Container {

private String hello;

private Map parameterMap = new HashMap();

public Map getParameterMap() {

return parameterMap;

}

}

将Container传递给JNI的Master Class:

public class MyClazz {

public doProcess() {

Container container = new Container();

container.getParameterMap().put("foo","bar");

manipulateMap(container);

}

public native void manipulateMap(Container container);

}

相关C函数:

JNIEXPORT jint JNICALL Java_MyClazz_manipulateMap(JNIEnv *env, jobject selfReference, jobject jContainer) {

// initialize the Container class

jclass c_Container = (*env)->GetObjectClass(env, jContainer);

// initialize the Get Parameter Map method of the Container class

jmethodID m_GetParameterMap = (*env)->GetMethodID(env, c_Container, "getParameterMap", "()Ljava/util/Map;");

// call said method to store the parameter map in jParameterMap

jobject jParameterMap = (*env)->CallObjectMethod(env, jContainer, m_GetParameterMap);

// initialize the Map interface

jclass c_Map = env->FindClass("java/util/Map");

// initialize the Get Size method of Map

jmethodID m_GetSize = (*env)->GetMethodID(env, c_Map, "size", "()I");

// Get the Size and store it in jSize; the value of jSize should be 1

int jSize = (*env)->CallIntMethod(env, jParameterMap, m_GetSize);

// define other methods you need here.

}

值得注意的是,我并没有为在方法本身中初始化methodIDs和类而烦恼. this SO Answer向您展示了如何缓存它们以便重复使用.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值