简体   繁体   中英

Making generic calls with JAVA JNI and C++

I am working with JNI and I have to pass in some generic types to the C++. I am stuck with how to approach this on the C++ side

HashMap<String, Double[]> data1 ; 
ArrayList<ArrayList<String>> disc ;

I am new to JNI and looked around but could not find much help. Can some one help me how to write JNI code for this please. Any reference to material on the net would be very helpful too.

Short answer: You cannot.

Long answer: Type Erasure : http://download.oracle.com/javase/tutorial/java/generics/erasure.html

Consider a parametrized instance of ArrayList<Integer> . At compile time, the compiler checks that you are not putting anything but things compatible to Integer in the array list instance.

However, also at compile time (and after syntactic checking), the compiler strips the type parameter, rendering ArrayList<Integer> into Arraylist<?> which is equivalent to ArrayList<Object> or simply ArrayList (as in pre JDK 5 times.)

The later form is what JNI expects (because of historical reasons as well as due to the way generics are implemented in Java... again, type erasure.)

Remember, an ArrayList<Integer> is-a ArrayList . So you can pass an ArrayList<Integer> to JNI wherever it expects an ArrayList . The opposite is not necessarily true as you might get something out of JNI that is not upwards compatible with your nicely parametrized generics.

At this point, you are crossing a barrier between a typed, parametrized domain (your generics) and an untyped one (JNI). You have to encapsulate that barrier pretty nicely, and you have to add glue code and error checking/error handling code to detect when/if things don't convert well.

The runtime signature is just plain HashMap and ArrayList - Generics are a compile-time thing.

You can use javah to generate a C header file with correct signatures for native functions.

It depends on what you're trying to map to and if they are yours to change.

Here are a few directions I'd try to go about (if i were you, that is :) ):

  1. Using SWIG templates ( related SO question ) or TypeMaps .
  2. Doing some reflection magic to be used against your-own-custom-generic-data-passing native API ( haven't figured the details out, but if you want to follow on it, tell what you've got on the C++ side ).

This has been asked before and you might want to resort to Luis' arrays solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM