首页 > 解决方案 > 无法访问 java 中的 c++ 对象并在 android studio 中跨 JNI 层从 long objectptr 获取错误结果 c++ 函数

问题描述

我试图通过创建 c++ 类的指针并将其存储在 java 中的 long 值中作为 java 类中的数据成员来调用 c++ 方法,并尝试从通过传递存储的 long 值并将其传递给本机方法而创建的对象访问调用 c++ 方法我想打电话。我正在将其转换为本机方法中的 Numbers 类,即我想要访问其方法的类。但是给出错误的输出。我猜是一些垃圾值。我对这个概念完全陌生。任何人都可以告诉我确切的问题或纠正错误。

现在,我正在尝试创建 Numbers 类的非常简单的示例,该类支持对两个数字、add、mul、sub 和一个构造函数来初始化数字 - a 和 b 的简单操作。请找到各种类的代码:

MainActivity.java

package com.example.maths;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private long  numberptr = 0; //c++ object reference

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Creating Number object
        numberptr = createNumber();

        //Performing add operation
        int result = nativeAdd(numberptr);

        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text );
        tv.setText(stringFromJNI() + "result is " + result);
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    //Native method to create instance of Number (c++ class) and store it in java in numberptr long object
    public native long createNumber();

    public native int nativeAdd(long numberptr);
}

本机-lib.cpp

#include <jni.h>
#include <string>
#include "Numbers.h"

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_maths_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}
extern "C"
JNIEXPORT jlong JNICALL
Java_com_example_maths_MainActivity_createNumber(JNIEnv *env, jobject thiz) {
    // TODO: implement createNumber()
    return reinterpret_cast<jlong>(new Numbers(3, 4));
}

extern "C"
JNIEXPORT jint JNICALL
Java_com_example_maths_MainActivity_nativeAdd(JNIEnv *env, jobject thiz, jlong numberptr) {
    // TODO: implement nativeAdd()
    Numbers* num = reinterpret_cast<Numbers *>(numberptr);
    return num->add();
}

数字.h

#ifndef MATHS_NUMBERS_H
#define MATHS_NUMBERS_H


class Numbers {
    int a, b;

public:
    Numbers(int,int);
    int add();
    int mul();
    int sub();
};


#endif //MATHS_NUMBERS_H

数字.cpp

#include "Numbers.h"

Numbers::Numbers(int a, int b) {
    a = a;
    b = b;
}

int Numbers::add() {
    return a+b;
}

int Numbers::mul() {
    return a*b;
}

int Numbers::sub() {
    return a-b;
}

CmakeLists.txt

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             native-lib.cpp
             Numbers.cpp
        )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

请告诉我问题是什么或应该如何准确处理。提前致谢。

标签: javac++java-native-interface

解决方案


推荐阅读