Akhil Dabral
Akhil Dabral

Reputation: 900

Shared Object usage in Android application

I have a C++ Shared Object provided by another developer. I do not have the C++ code with me, just the .so file. Can I use the .so file directly in my Android application. I have done some JNI programming but it uses C++ code itself and not the .so directly. My issue is that I do not have the C code. Is there any way possible to achieve this?

Upvotes: 3

Views: 2088

Answers (2)

Alex Cohn
Alex Cohn

Reputation: 57183

Yes, you can use a precompiled shared object in a JNI app. First of all, make sure that it is built for the right platform. This involves ABI, like x86 or armeabi-v7a, but also the OS platform level; an .so built for android-21 will probably fail to load on android-19.

Second, you need a Java class (or classes) that describe the native methods exposed by the shared object. Not only the method names and signatures must be correct, but also the Java class name and full package name are hardcoded in the .so. Some native methods should be declared static, others - not. Quite often the underlying C code does not care.

It may be quite tricky to reverse engineer the these method signatures from the native binary. But sometimes you can simply guess, like if you see an exported function Java_com_example_hellojni_HelloJni_stringFromJNI then you need to supply a Java class:

package com.example.hellojni;
public class HelloJni {
    public native String stringFromJNI();
}

You don't have to worry about private vs public native methods. JNI ignores this attribute.

The shared object may be expecting some callbacks on the Java side. If it looks for a certain application-specific class and method within it, and you don't provide it, the app will crash.

Upvotes: 2

user2543253
user2543253

Reputation: 2173

Option 1 is to write a wrapper library with Java native methods accessing the functions of your .so.

Option 2 is using JNA. JNA can access arbitrary library functions, if you tell it the parameter structure and return type. Depending on how complex the interface is, this might be easy or not. There's instructions for Android in the www folder of the JNA project.

In both cases you need the corresponding header files of your .so or at least a detailed documentation, so you don't have to guess parameter types.

Upvotes: 1

Related Questions