简体   繁体   中英

Create react-native Native Module in C or C++ using Android NDK?

Must I create a Java Native Interface (JNI) in order to access C or C++ code from a react-native Native Module for Android?

My goal is to re-use common C and C++ algorithms (non-UI ) in a react-native Native Module that supports both Android and iOS. It is simple to call C from an Objective C *.m module, or C++ from an Objective C++ *.mm module. However, a react-native Native Module for Android implements the Native Module code in java.

https://facebook.github.io/react-native/docs/native-modules-android.html#content

The Android NDK allows you to write Android code in C or C++. The Android NDK works well with C++ frameworks such as Qt 5.6 . I do not understand how I can cross the javascript to react-native Native Module while avoiding a java JNI?

Thanks in advance for any tips or direction,

I recently had to do this on a React Native project, and I couldn't find a way around it without using JNI. To do so you essentially have to make code for the JS to Java bridge, and then more code for the Java to C (via JNI) bridge, and then back out to JS.

If you're only passing primitives then it's pretty easy as JNI can deal with type conversion, for example a Java int to a jint (which is an int typedef) in C, but if you're passing complex data types then you have to write code to get a C struct out a JNI jobject by telling JNI what fields your class has and what types those fields are. I found easier to write up utility functions to do this. It's a lot of initial setup and boring code, but once you get going and are used to it it's not that difficult. The JNI Spec is great for reference, it just doesn't tell you how you should use it.

I have a github project that uses JNI to pass around some example classes. This blog article explains all the setup steps for JNI, and if you're already comfortable with that, it gets into dirty detail in the "Real World JNI" section. Let me know if you have any questions about it!

If you are willing to do a little extra work you can use Djinni .

This project generates interface bindings for Objective-C and Java. Once you create the wrapper code for C++, you can create Java and Objective-C classes that integrate with React Native. Thus React will call Obj-C/Java which will call C++. Profit.

It will be cool to see how this works for you, I have not seen anyone do this yet.

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