Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 288
Ed of the Mountain Avatar asked Apr 12 '16 13:04

Ed of the Mountain


1 Answers

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!

like image 69
rdixonbpk Avatar answered Sep 17 '22 06:09

rdixonbpk