java - 在 JNI 层中创建 c++ 实例,将其作为长对象传递给 Java 类,但方法返回垃圾值
问题描述
我是 JNI 概念和 C++ 与 Java 之间交互概念的新手。我创建了一个 Numbers 类,并希望将一个 java 包装器添加到抽象本机层。我创建了一个 java 类 Maths.java 并添加了我需要调用的函数,并为 Java 中的每个方法调用了本机方法。首先,我在 MainActivity.java 中创建了 Maths 类的实例,当我们创建 Maths 类的对象时,它调用本机方法在 c++ 中创建 Numbers 的实例,并在 Java 中为 Numbers 指针设置 long 值。我通过在 native-lib.cpp(跨 JNI 层)中使用这个 long 值来调用各种本机函数,方法是将其类型转换为 c++ 类。但是当我调用这些函数时,我得到了垃圾值。
我附上代码。有人可以告诉我确切的问题以及为什么它不起作用。
主要活动.java
package com.example.maths2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public String TAG = "MainActivity.java";
// 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);
//testing Maths class
Log.d(TAG, "Creating Maths Object: ");
Maths math = new Maths(3, 5);
Log.d(TAG, "Calling addition: ");
int addResult = math.add();
Log.d(TAG, "Calling subtraction: ");
int subResult = math.sub();
Log.d(TAG, "Calling Multiplication: ");
int mulResult = math.mul();
//deleting c++ object
math.destroy();
// Example of a call to a native method
TextView tv = findViewById(R.id.sample_text);
//Testing the values
tv.setText(stringFromJNI() + "Add: " + addResult + "Sub: " + subResult + "Mul : " + mulResult);
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
}
数学.java
package com.example.maths2;
public class Maths {
private int a, b;
private long numberptr = 0L; //Stores c++ pointer to Numbers object
static {
System.loadLibrary("native-lib");
}
public Maths(int a, int b) {
a = a;
b = b;
createNumberInstance(a, b);
}
public int add() {
return nativeAdd();
}
public int sub() {
return nativeSub();
}
public int mul() {
return nativeMul();
}
public void destroy() {
numberptr = 0L;
nativeDestroy();
}
//Native Methods
public native void createNumberInstance(int a, int b);
public native int nativeSub();
public native int nativeAdd();
public native int nativeMul();
public native void nativeDestroy();
}
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} )
本机 lib.cpp
#include <jni.h>
#include <string>
#include "Numbers.h"
// Get pointer field
jfieldID getPtrFieldId(JNIEnv * env, jobject obj)
{
static jfieldID ptrFieldId = 0;
if (!ptrFieldId)
{
jclass c = env->GetObjectClass(obj);
ptrFieldId = env->GetFieldID(c, "numberptr", "J");
env->DeleteLocalRef(c);
}
return ptrFieldId;
}
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_maths2_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_maths2_Maths_createNumberInstance(JNIEnv *env, jobject thiz, jint a, jint b) {
// TODO: implement createNumberInstance()
env->SetLongField(thiz, getPtrFieldId(env, thiz), (jlong) new Numbers(a, b));
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_example_maths2_Maths_nativeSub(JNIEnv *env, jobject thiz) {
// TODO: implement nativeSub()
Numbers* numb = (Numbers*) env->GetLongField(thiz, getPtrFieldId(env, thiz));
return numb->add();
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_example_maths2_Maths_nativeAdd(JNIEnv *env, jobject thiz) {
// TODO: implement nativeAdd()
Numbers* numb = (Numbers*) env->GetLongField(thiz, getPtrFieldId(env, thiz));
return numb->sub();
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_example_maths2_Maths_nativeMul(JNIEnv *env, jobject thiz) {
// TODO: implement nativeMul()
Numbers* numb = (Numbers*) env->GetLongField(thiz, getPtrFieldId(env, thiz));
return numb->mul();
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_maths2_Maths_nativeDestroy(JNIEnv *env, jobject thiz) {
// TODO: implement nativedestroy()
Numbers* numb = (Numbers*) env->GetLongField(thiz, getPtrFieldId(env, thiz));
delete numb;
}
数字.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;
}
数字.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
请有人告诉我应该做什么或者可以纠正错误的事情。
解决方案
推荐阅读
- javascript - 用户保存 HTML5 音频时如何控制文件名?
- android - 将一张图片旋转到另一张图片上方
- javascript - 如何在javascript中更改urlpath
- javascript - 从使用 Array.join(' ') 创建的字符串中删除元素。如何在开头保留空格?
- docker - “docker create”和“docker start”之间的“-a”和“-i”有什么区别
- android - 如何在片段管理器中使用扩展方法
- c - 修改linux中注册字符设备中的文件操作
- mysql - mysql错误操作数应该有1列存储过程
- powershell - 自定义徽标/壁纸更改
- javascript - 关于逻辑运算符&&的理解题