raja.b
raja.b

Reputation: 21

Running a C binary from an android application : particulare case

I have a C project that I want to launch on Android.

I compiled the project using the NDK, generate the binary and embed it in an application to launch it. The project uses autotools, I used androgenizer to generate and adapt the Android.mks. It also uses openssl, so I compiled it for android following this, and binary uses compiled libcrypto.so.

The application only does :

Here is a piece of code

Process mybinProcess;
File target = new File(getFilesDir(), "mybin");
InputStream in = getResources().openRawResource(R.raw.mybin);

try {
    OutputStream out = new FileOutputStream(target);
    FileUtils.copy(in, out);
    FileUtils.chmod(target, 0755);

if(target.exists()){
    String[] command = {target.getAbsolutePath()};
    mybinProcess = Runtime.getRuntime().exec(command);
    BufferedReader output = FileUtils.getOuput(mybinProcess);
    BufferedReader error = FileUtils.getError(mybinProcess);

    // [...] print stdout et stderr

    mybinProcess.waitFor();
    int exitval=mybinProcess.exitValue(); //exit value is 1

The stdout gives me a syntax error on the binary :

/data/data/com.myproject.mybin/files/mybin[1]: syntax error: ' 4   4' unexpected

And when I tried to launch the binary from the adb shell, got that error

root@generic_x86:/data/user/0/com.myproject/files # ./mybin
/system/bin/sh: ./mybin: not executable: 32-bit ELF file

I opened mybin in an hex editor, the syntax error comes before the string of the lib /usr/lib/libc.so.1. But on the emulator the directory /usr doesn't exist. I think it comes from the ndk, the last compilation line of the ndk-build make an include from <ndk>/platforms/android-19/arch-arm/usr/lib. Besides, in <ndk>/platforms/android-19/arch-arm/usr/lib there is only libc.so and not libc.so.1.

Any idea on where I can search to fix it, make it works?


My configuration :

Upvotes: 1

Views: 2304

Answers (1)

Gary Bak
Gary Bak

Reputation: 4798

Building an executable to run on Android is possible, but not the right approach IMO, You should build a JNI interface to your native binary library and make calls into the C library.

There is a simple example here:

http://developer.android.com/ndk/samples/sample_hellojni.html

We have had a lot of success using javacpp to generate the JNI code if you have a lot of JNI calls. If you need only one or two calls, I'd probably write it by hand.

Upvotes: 4

Related Questions