Storing multiple values in C++/C# using NDK

Martin Dina Putra
Bootcampers
Published in
3 min readAug 8, 2022

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 the HashMap class within the package that it’s residing
  • jmethodID init = env->GetMethodID(mapClass, “<init>”, “(I)V”);: construct the init method or in other words, the constructor.
  • jmethodID put = env->GetMethodID(mapClass, “put”, “(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;”);: construct the put method so that we add new entries
  • jobject hashMap = env->NewObject(mapClass, init, map_len);: call the init function from the HashMap class and provide the argument of the initial size of the map with map_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.

--

--