Java C++ Android 包装器:如何包装 c++模板
我正在开发一个 android 项目(一个 3d 实时应用程序),并且想使用我编写的 c++ 库。由于它依赖于模板,我正在寻找一个好的解决方案来围绕它编写 Java 包装器。
我的一个想法是在创建对象时在 JNI 调用中包含 java 类名。例如,我像这样实例化一个 Java 类:
//java
A a = new A(Integer.class());
//jni call
if(strcmp("java.lang.integer", className) == 0) return (jlong) new A<int>();
else if(strcmp("java.lang.float", className) == 0) return (jlong) new A<float>();
else if( .... )
这个解决方案的问题是,每当我想使用新的数据类型时,我都必须添加另一个 elseif 代码块并再次编译 C++ 代码。
I'm working on an android project (a 3d realtime application) and would like to use a c++ library I've written. Since it's relying on templates I'm looking for a good solution to write a Java wrapper around it.
One idea I had, was to include the java class name in the JNI call when I create an object. For example I instantiate a Java class like this:
//java
A a = new A(Integer.class());
//jni call
if(strcmp("java.lang.integer", className) == 0) return (jlong) new A<int>();
else if(strcmp("java.lang.float", className) == 0) return (jlong) new A<float>();
else if( .... )
The problem with this solution is, that whenever I want to use a new data type I have to add another elseif code block and compile the c++ code again.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请记住,Java 中只有 8 种基本类型。如果为其中每一个添加一个 if-else,您将能够处理任何基本类型参数。
如果您还添加了
jobject
的情况,您还可以使用它来处理任何对象类型。请注意正确处理 JNI 对象引用。Remember that there are only 8 primitive types in Java. If you add one if-else for each of those, you will be able to handle any primitive type argument.
If you also add a case for
jobject
you can also use that to handle any object type. Just be careful to handle your JNI object references correctly.