Maksim Dmitriev
Maksim Dmitriev

Reputation: 6209

System.load for library loading

I loaded a library from the /system/libs/my_lib.so directory successfully. How can I use the C/C++ functions which are defined in this library?

public class MainFrom extends Activity {

    private static final String LOG_TAG = "MainFrom";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main); 
        // How to use the functions of test_lib.so? 

        /*
            java.lang.UnsatisfiedLinkError: stringFromC


        String s1 = stringFromC(), s2 = stringFromCpp();

        Log.w(LOG_TAG, stringFromC());   
        Log.w(LOG_TAG, stringFromCpp());  */
    }

    public native String stringFromC();
    public native String stringFromCpp();

    static {
        try { 
            System.load("/system/lib/test_lib.so");
            Log.i(LOG_TAG, "MainFrom. Success!");
        } catch (UnsatisfiedLinkError e) {
            Log.e(LOG_TAG, "MainFrom. UnsatisfiedLinkError");
        }
    }

}

stringFromC and stringFromCpp exist in .c and .cpp files which were compiled to test_lib.so

Upvotes: 3

Views: 10537

Answers (3)

Tianyu Wang
Tianyu Wang

Reputation: 1

Starting in Android 7.0, the system prevents apps from dynamically linking against non-NDK libraries, which may cause your app to crash. This change in behavior aims to create a consistent app experience across platform updates and different devices.

android 7.0 changes description

Upvotes: 0

Maksim Dmitriev
Maksim Dmitriev

Reputation: 6209

I have solved my problem.

It was necessary to write

System.load("/system/lib/libtest_lib.so");

instead of

System.load("/system/lib/test_lib.so");

So strange. If I run

adb shell 
ls /system/lib

I will see test_lib.so file. Why is it correctlly to load library using lib prefix?

Upvotes: 4

Nishant Rajput
Nishant Rajput

Reputation: 2063

you need to put LOCAL_CPPFLAGS := $(YOURMODULE_CPPFLAGS)and in LOCAL_SRC_FILES := yourfile.cpp in your Android.mk file to compile .cpp file with android NDK.

Hope it will help you.

Upvotes: 0

Related Questions