使用 JAVA JNI 和 C++ 进行通用调用

Making generic calls with JAVA JNI and C++(使用 JAVA JNI 和 C++ 进行通用调用)

本文介绍了使用 JAVA JNI 和 C++ 进行通用调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JNI,我必须将一些泛型类型传递给 C++.我不知道如何在 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 ;

我是 JNI 的新手,环顾四周,但找不到太多帮助.有人可以帮助我如何为此编写 JNI 代码.任何参考网络上的材料都会非常有帮助.

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.

推荐答案

简答:你不能.

长答案:键入擦除:http://download.oracle.com/javase/tutorial/java/generics/erasure.html

考虑 ArrayList 的参数化实例.在编译时,编译器会检查您没有在数组列表实例中放入任何与 Integer 兼容的东西.

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.

但是,同样在编译时(以及在语法检查之后),编译器会剥离类型参数,将 ArrayList 呈现为 Arraylist,即等同于 ArrayList<Object> 或简单地 ArrayList (在 JDK 5 之前).

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.)

后一种形式是 JNI 所期望的(由于历史原因以及 Java 中泛型的实现方式……再次,类型擦除.)

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.)

请记住,ArrayList 是一个 ArrayList.因此,您可以将 ArrayList<Integer> 传递给 JNI,只要它需要 ArrayList.相反的情况不一定正确,因为您可能会从 JNI 中得到一些与您的参数化的泛型不兼容的东西.

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.

此时,您正在跨越类型化、参数化的域(您的泛型)和无类型的域(JNI)之间的障碍.您必须很好地封装该障碍,并且您必须添加胶水代码和错误检查/错误处理代码来检测何时/如果事情不能很好地转换.

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.

这篇关于使用 JAVA JNI 和 C++ 进行通用调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 JAVA JNI 和 C++ 进行通用调用

基础教程推荐