Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an int from native function(c++, jni) crashes application

Trying to figure out why c++ function call returning an int crashes the whole application without any errors/warnings.

Here is working code:


    jint Java_org_ntorrent_DummyTorrentInfoProvider_next(
            JNIEnv * env, jobject obj, jint number)
    {
        jint test = rand();
        __android_log_print(ANDROID_LOG_DEBUG, "HelloNDK!", "rand() = %d", test);

        return number;
    }

And this code crashes application without warnings:


    jint Java_org_ntorrent_DummyTorrentInfoProvider_next(
            JNIEnv * env, jobject obj, jint number)
    {
        jint test = rand();
        __android_log_print(ANDROID_LOG_DEBUG, "HelloNDK!", "rand() = %d", test);

        return number + test;
    }

Before the application crashes i can see my log message(__android_log_print) in log cat

EDIT: Even if I replace "number + test" with "1" the application still crashing... It only works if I return "number"...

EDIT#2: Java-side code:


package org.ntorrent;

import java.util.ArrayList;
import java.util.Random;

public class DummyTorrentInfoProvider implements TorrentInfoProvider {

    public native Integer next(Integer number);

    //public Integer next() { return _random.nextInt(); }

    public native void test();

    private Random _random = new Random(100);

    @Override
    public ArrayList getTorrents() {
        test();
        ArrayList torrents = new ArrayList();
        torrents.add(
                new TorrentInfo("test torrent number 1", next(1),  3f, 5f));
        torrents.add(
                new TorrentInfo("test torrent number 2", next(2), 4f, 15f));
        torrents.add(
                new TorrentInfo("test torrent number 555"));
        torrents.add(
                new TorrentInfo("test torrent number 3", next(3), 13f, 5f));
        return torrents;
    }

    static {
        System.loadLibrary("test");
    }
}
like image 517
6opuc Avatar asked May 14 '12 18:05

6opuc


1 Answers

jint Java_org_ntorrent_DummyTorrentInfoProvider_next(
    JNIEnv * env, jobject obj, jint number)

and

public native Integer next(Integer number);

Do not match. An Integer is an Object, while an int is a primitive.

If your native code uses jint, your java code should use int in the declaration of the native method.

(If you wish to pass an Integer, you'll need to treat it as a jobject on the native side, and jump through hoops to access it - it's probably easier to use int/jint and do any necessary conversion to from Integer in the java side)

like image 169
Chris Stratton Avatar answered Oct 06 '22 00:10

Chris Stratton