Storing multiple values in C++/C# using NDK
This post requires knowledge on what and how to write C++/C# code using NDK(Native Development Kit) and interact with them using JNI(Java Native Interface), so if you haven’t read the previous post, go check them out!
We have covered how we can use NDK to hide sensitive data in the previous post. It adds another layer of security for our attackers by generating .so
files which are much harder to decrypt than regular Java/Kotlin codes.
Last time we ran through the basics of NDK and step by step on how to implement it in an Android project and store a single value in our C++ class. This time, we will talk about how can we store multiple values and retrieve them from Java/Kotlin class.
Often times we want to have different baseUrl
values for each deployment environment. That means we have to store & retrieve multiple values in our cpp
class. As I’ve mentioned in the previous post, we can achieve this by refactoring our cpp
class and making it return a List
or Map
instead of a single String
.
Please note that there are many ways to do it but this one is the solution that worked for me after a lot of stackoverflow digging.
So the idea is that we construct the java HashMap
class manually using reflection in our cpp
class, then populate the map that we initialized with the values that we want our function to return. Ready? here we go
Now this may look a bit overwhelming, but we will attempt to break it down
jclass mapClass = env->FindClass(“java/util/HashMap”)
: find theHashMap
class within the package that it’s residingjmethodID init = env->GetMethodID(mapClass, “<init>”, “(I)V”);
: construct theinit
method or in other words, the constructor.jmethodID put = env->GetMethodID(mapClass, “put”, “(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;”);
: construct theput
method so that we add new entriesjobject hashMap = env->NewObject(mapClass, init, map_len);
: call theinit
function from theHashMap
class and provide the argument of the initial size of the map withmap_len
- Please note that I have renamed the function to
adrNativeValues
, later on, we will also have to modify our Java/Kotlin class to match the name
map_len
doesn’t have to be exactly the same size as you put your values into the map. As you may have known, java’s HashMap
class has the ability to resize itself when it runs out of space. But for the sake of optimization, it’s best that we provide the initial size of the map that fits all of our entries to avoid resizing.
That’s it for the cpp
part, All that’s left to do is to modify our Java/Kotlin class and change the external
function to return a Map
instead of a String
!
That’s it, folks! Thanks for reading. I hope you find these blogs useful 😊
Please don’t hesitate to let me know in the comments if you have any feedback/questions.