Java – returning an int from a native function (C, JNI) causes the application to crash

Trying to figure out why returning an int from a C function call causes the entire application to crash without any errors / warnings

This is the 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;
    }

This code crashes the application without warning:

jint Java_org_ntorrent_DummyTorrentInfoProvider_next(
            jnienv * env,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 "digital test" with "1", the application still crashes... It only works when 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");
    }
}

Solution

jint Java_org_ntorrent_DummyTorrentInfoProvider_next(
jint Java_org_ntorrent_DummyTorrentInfoProvider_next(
    jnienv * env,jint number)

and

public native Integer next(Integer number);

Non conformity Integer is an object and int is a primitive

If your native code uses jint, your Java code should use int

(if you want to pass an integer, you need to treat it as a native job and skip the hoop to access it - it may be easier to use int / jint and make any necessary transformations in integer. Java)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>