Not able to access c++ objects in java and getting wrong results c++ functions from long objectptr across JNI Layer in android studio

huangapple 未分类评论48阅读模式
英文:

Not able to access c++ objects in java and getting wrong results c++ functions from long objectptr across JNI Layer in android studio

问题

我试图通过创建 C++ 类的指针并将其存储为 Java 类中的长整型数据成员然后尝试从通过传递存储的长整型值创建的对象调用 C++ 方法并将其传递给我想要调用的本地方法我将其转换为本地方法中的 Numbers 类这是我想要访问其方法的类
但是输出错误我猜是一些垃圾值我对这个概念完全是新手有人可以告诉我确切的问题或者纠正我可能犯的错误

目前我正在尝试一个非常简单的例子创建支持对两个数字执行简单操作的 Numbers 类包括加法乘法减法以及一个构造函数来初始化数字 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++ 对象引用
    
        // 在应用启动时用于加载 'native-lib' 库。
        static {
            System.loadLibrary("native-lib");
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // 创建 Number 对象
            numberptr = createNumber();
    
            // 执行加法操作
            int result = nativeAdd(numberptr);
    
            // 调用本地方法的示例
            TextView tv = findViewById(R.id.sample_text);
            tv.setText(stringFromJNI() + "result is " + result);
        }
    
        /**
         * 由 'native-lib' 本地库实现的本地方法,
         * 该库与此应用程序一起打包。
         */
        public native String stringFromJNI();
    
        // 本地方法,用于创建 Number(C++ 类)的实例,并将其存储在 Java 中的 numberptr 长整型对象中
        public native long createNumber();
    
        public native int nativeAdd(long numberptr);
    }

Native-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: 实现 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: 实现 nativeAdd()
        Numbers* num = reinterpret_cast<Numbers *>(numberptr);
        return num->add();
    }

Numbers.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

Numbers.cpp

    #include "Numbers.h"
    
    Numbers::Numbers(int a, int b) {
        this->a = a;
        this->b = b;
    }
    
    int Numbers::add() {
        return a + b;
    }
    
    int Numbers::mul() {
        return a * b;
    }
    
    int Numbers::sub() {
        return a - b;
    }

CmakeLists.txt

    # 有关在 Android Studio 中使用 CMake 的更多信息请阅读文档https://d.android.com/studio/projects/add-native-code.html
    
    # 设置构建所需的 CMake 的最低版本
    cmake_minimum_required(VERSION 3.4.1)
    
    # 创建并命名库将其设置为 STATIC 或 SHARED并提供到其源代码的相对路径
    # 您可以定义多个库CMake 会为您构建它们
    # Gradle 会自动将共享库与 APK 打包在一起
    add_library( # 设置库的名称
                 native-lib
    
                 # 将库设置为共享库
                 SHARED
    
                 # 提供到您的源文件的相对路径
                 native-lib.cpp
                 Numbers.cpp
            )
    
    # 搜索指定的预构建库并将路径存储为变量
    # 由于 CMake 默认在搜索路径中包括系统库您只需指定您希望 CMake 定位的 NDK 公共库的名称
    # CMake 会在完成构建之前验证库是否存在
    find_library( # 设置路径变量的名称
                  log-lib
    
                  # 指定要让 CMake 定位的 NDK 库的名称
                  log )
    
    # 指定 CMake 应链接到目标库的库
    # 您可以链接多个库例如您在此构建脚本中定义的库预构建的第三方库或系统库
    target_link_libraries( # 指定目标库
                           native-lib
    
                           # 将目标库链接到 NDK 中包含的 log 库
                           ${log-lib} )

请问还有其他需要帮助的地方吗?

英文:

I am trying to call c++ methods by creating a pointer of c++ class and storing it in long value in java as data member in java class and trying to access call c++ methods from object created by passing the long value stored and passing it to native methods I want to call. I am converting this to Numbers class in native methods, the class whose methods I want to access.
But giving wrong output. Some garbage value I guess. I am completely new to this concept. Can anybody tell me exact issue or correct the errors if made.

Right now, I am trying with very simple example of creating Numbers class that supports simple operations on two numbers, add,mul,sub and one constructor to initialize the numbers - a and b.
Please find the code for various classes:

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 &#39;native-lib&#39; library on application startup.
    static {
        System.loadLibrary(&quot;native-lib&quot;);
    }

    @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() + &quot;result is &quot; + result);
    }

    /**
     * A native method that is implemented by the &#39;native-lib&#39; 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);
}

Native-lib.cpp

#include &lt;jni.h&gt;
#include &lt;string&gt;
#include &quot;Numbers.h&quot;

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

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

Numbers.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

Numbers.cpp

#include &quot;Numbers.h&quot;

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} )

Please tell me what's the issue or how it should be exactly handled. Thanks in advance.

huangapple
  • 本文由 发表于 2020年5月29日 14:31:07
  • 转载请务必保留本文链接:https://java.coder-hub.com/62079941.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定