英文:
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 '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);
}
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: 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();
}
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) {
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.
专注分享java语言的经验与见解,让所有开发者获益!
评论