Krzysztof Kubicki
Krzysztof Kubicki

Reputation: 676

Android loadLibrary .so calling methods and constructor

I've checked here and it seems to be no answer for my particular question. I got to know that I one can use C .so library and refer the methods in it by somewhat overriding the library native methods like below:

@SuppressWarnings("JniMissingFunction")
    public class MyNativeMethods {
    static {
        System.loadLibrary("libraryWithSoExtension");
}
public native boolean init();
} 

My probelem is that I'd like to call the constructor in this lib. The lib contains only couple of classes, where each of them contains 1 or 2 methods. I see from here:

How to call methods on .so library in Android studio

that I do not need any h, c or jni (do I really?).

Questions:

  1. Could you confirm that I do not need any JNI files to access native methods from .so file?
  2. Can one actually access a constructor as described above and how does the importing work if it's possible
  3. MAVEN/GRADLE - Is it correct that a will not work for .so file? And it's equivalent in gradle also?

Thank you in advance.

Upvotes: 0

Views: 2961

Answers (2)

Oo.oO
Oo.oO

Reputation: 13375

I am not sure whether this is what you are looking for, but take a look here:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo025

you will find there super simple code with C++ being called via JNI wrapper from Java.

Upvotes: 0

Alex Cohn
Alex Cohn

Reputation: 57173

If you have a prebuilt .so file that implements some native methods, you don't need its sources to build your project in Android Studio.

The catch is that the names of native methods and classes that contain these methods are hardcoded, e.g. Java_com_example_test_MainActivity_stringFromJNI exported function in a shared library libmy.so is fit to

package com.example.test;
public class MainActivity extends Activity {
  static {
    System.loadLibrary("my");
  }
  public native String stringFromJNI();
}

and not some other Java class or method (there are tools to make such reverse engineering harder).

You can use the javah command to generate C declarations for your native methods, but it cannot reverse engineer the Java class that fits given library. But it will let you declare a native constructor, if you really want one.

Gradle plugin for Android Studio will pack the so files from src/main/jniLibs into your APK, unless you set a different jniLibs.srcDir directory in your build.gradle.

Upvotes: 2

Related Questions