Making generic calls with JAVA JNI and C++

后端 未结 3 1576
借酒劲吻你
借酒劲吻你 2021-01-13 15:23

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

        
相关标签:
3条回答
  • 2021-01-13 16:12

    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.

    0 讨论(0)
  • 2021-01-13 16:14

    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.

    0 讨论(0)
  • 2021-01-13 16:20

    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.

    0 讨论(0)
提交回复
热议问题