java 调用c++类对象方法
背景描述
-
java如何通过jni native方法调用c++类对象,通过传递对象的句柄,来控制调用类的成员函数以及获取成员变量的值,并手动释放类对象
-
废话不多说,直接上代码。
-
jni对应的cpp
#include <stdlib.h> #include <string> #include "class_test.h" #include "test_class_jni.h" //返回类对象实例化之后的地址,地址的存储数据类型为long JNIEXPORT jlong JNICALL Java_com_test_jni_utils_ClassTest_init(JNIEnv *env, jobject thisObj) { Test* pTest = NULL; pTest = new Test(); pTest->init(); return jlong(pTest); } //传对象地址,并且调用对象的成员函数,对某一个成员变量进行自增长+1 JNIEXPORT jint JNICALL Java_com_test_jni_utils_ClassTest_addSum(JNIEnv *env, jobject thisObj, jlong nativeId) { Test* p = (Test*)nativeId; int sum = p->add(); return sum; } //主动释放对象空间 JNIEXPORT jint JNICALL Java_com_test_jni_utils_ClassTest_deInit(JNIEnv *env, jobject thisObj, jlong nativeId) { Test* p = (Test*)nativeId; if (p) { delete p; p = NULL; } return 0; } -
jni对应的头文件
/* DO NOT EDIT THIS FILE - it is machine generated */ #include "jni.h" #ifndef _Included_com_jni_object_array #define _Included_com_jni_object_array #ifdef __cplusplus extern "C" { #endif /* * Class: com_test_jni_utils_ClassTest * Method: createInit * Signature: (Ljava/lang/String;Ljava/lang/String;)I */ JNIEXPORT jlong JNICALL Java_com_test_jni_utils_ClassTest_init(JNIEnv*, jobject); JNIEXPORT jint JNICALL Java_com_test_jni_utils_ClassTest_addSum(JNIEnv*, jobject, jlong); JNIEXPORT jint JNICALL Java_com_test_jni_utils_ClassTest_deInit(JNIEnv*, jobject, jlong); #ifdef __cplusplus } #endif #endif //_Included_com_jni_object_array -
类对象cpp
#include "class_test.h" Test::Test() { } Test::~Test() { } void Test::init() { m_index = 1; } void Test::push_result() { m_array.push_back(m_index); } int Test::add() { return m_index++; } -
类对象头文件
#pragma once #include <vector> class Test{ public: Test(); virtual ~Test(); void init(); public: void push_result(); int add(); private: int m_index; std::vector<int> m_array; };
-
-
linux下华为云jdk源码下载https://repo.huaweicloud.com/java/jdk/
-
centos系统下在线安装:
sudo yum install java-1.8.0-openjdk* -y
2119

被折叠的 条评论
为什么被折叠?



