0

I want to include .so file in the android project and want to call methods in java from within the c++ source code. I have included the .so file in jniLibs folder of android project. Can anyone tell me what is the procedure to implement it?

Thanks Ishan Jain

ishan jain
  • 681
  • 3
  • 10
  • 27

1 Answers1

0

If you already correctly put your .so file into jniLibs folder, the next step is to load ilinrary into memory and call methods from it. You can load library statically:

// Load that <your_lib_name>.so file 
static {
    System.loadLibrary("<your_lib_name>");
}

Then you need to declare the function according <your_lib_name>.so exported functions, e.g.:

private static final native <type_of_result> <function_name>(<type_of_param1> param1, <type_of_param2> param2);

and then you need to call the declared native function from Java:

(param1, param2);

Or you can load library dynamically via dlopen() like in this answer:

void *handle;
handle = dlopen("<your_lib_name>.so", RTLD_NOW);

...
// when you need old .so e.g. in onCreate()
OldSoHelper.loadOldSo();
...

// when you no need to call function from old .so
<TYPE_OF_RESULT> result = OldSoHelper.runFunFromOldSo(<PARAMETERS>);

...
// when you no need old .so e.g. in onDestroy()
OldSoHelper.unloadOldSo();
...
Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
  • Hi, Using the first method can we call any method inside any file from .so? – ishan jain Dec 10 '19 at 14:52
  • @ishanjain Only exported and you need JNI wrapper for them. – Andrii Omelchenko Dec 10 '19 at 19:19
  • @ishanjain From already build `.so` you can call only exported functions (to get list of exported functions see [this](https://stackoverflow.com/q/4514745/6950238) question). To call them from Java you need wrappers like in [that](https://stackoverflow.com/a/54885447/6950238) answer. – Andrii Omelchenko Dec 11 '19 at 07:02
  • one more question is that can we call already exported function without jni using above means private static final native ( param1, param2); – ishan jain Dec 11 '19 at 07:10
  • @ishanjain From Java - no, but you can call it from C/C++ part of your application (see [this](https://stackoverflow.com/questions/54782251/change-function-name-in-a-so-library/54885447#54885447) again). – Andrii Omelchenko Dec 11 '19 at 08:03