TL; DR我试图通过JNI向Java发送std::function
并在执行异步方法后将其用作Callable
(请参阅SBCallable
下) 。有没有办法做到这一点?
我试图通过JNI从C ++发起一个http请求,获取响应并将其发送回C ++。
我的Java NetworkManager
课程:
RequestQueue queue; //initialised in the constructor
private class SBCallable<V> implements Callable<V>{
private String response;
private int responseCode;
public SBCallable(/**function from c++ to call?**/) {
}
public setResponseCode(int responseCode)
{
this.responseCode = responseCode;
}
public setResponse(String response)
{
this.response = response;
}
public V call() throws Exception {
/**call my c++ function(response_code, response);**/
return null;
}
}
public void get(final String url,
final HashMap<String, String> mHeaders,
final SBCallable<Void> callback)
{
queue.add(new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
callback.setResponseCode(200); /**for test purposes**/
callback.setResponse(response);
callback.call();
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
})
{
@Override
public HashMap<String, String> getHeaders() throws AuthFailureError
{
return mHeaders;
}
});
}
我的C ++网络界面:
void get(const std::string &url,
const std::vector<std::pair<std::string, std::string>> &headers,
std::function<void(int, std::vector<char>)> response_fn)
JNI桥接代码:
// OnCreate, the app is saving a pointer to JVM.
void getHTTP(const std::string &url,
const const std::vector<std::pair<std::string, std::string>> &headers,
std::function<void(int, std::vector<char>)> response_fn_t /**callback function, with response code and content**/)
{
JavaVM* jvm = app.getJVM();
JNIEnv *env;
jvm->GetEnv((void**)&env,JNI_VERSION_1_6);
jobject headersMap = vectorStringPairToJavaHashMap(env, headers); // transforms from vector<pair<string, string>> to HashMap<String,String>
jstring url = env->NewStringUTF(url.c_str());
jclass clazz = env->FindClass("NetworkManager");
jobject object = env->NewObject(clazz, env->GetMethodID(clazz, "<init>", "()V"));
/**HOW DO I WRAP response_fn_t for Java to be able to call it? **/
env->CallObjectMethod(object, env->GetMethodID(clazz, "get", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V"), url, headersMap, /**wrapped function here**/);
}