从jni C++函数返回vector<Point>,可以按照以下步骤进行:
下面是一个示例代码:
C++代码:
#include <vector>
struct Point {
int x;
int y;
};
std::vector<Point> getPoints() {
std::vector<Point> points;
// 添加一些点到vector中
Point p1 = {1, 2};
Point p2 = {3, 4};
points.push_back(p1);
points.push_back(p2);
return points;
}
JNI代码:
#include <jni.h>
#include <vector>
struct Point {
int x;
int y;
};
extern "C" {
JNIEXPORT jobject JNICALL Java_com_example_MyClass_getPoints(JNIEnv* env, jobject obj) {
// 调用C++函数获取vector<Point>对象
std::vector<Point> points = getPoints();
// 创建ArrayList对象
jclass arrayListClass = env->FindClass("java/util/ArrayList");
jmethodID arrayListConstructor = env->GetMethodID(arrayListClass, "<init>", "()V");
jobject arrayListObj = env->NewObject(arrayListClass, arrayListConstructor);
// 获取ArrayList的add方法
jmethodID arrayListAddMethod = env->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z");
// 将vector<Point>中的点添加到ArrayList中
jclass pointClass = env->FindClass("com/example/Point");
jmethodID pointConstructor = env->GetMethodID(pointClass, "<init>", "(II)V");
for (const auto& point : points) {
jobject pointObj = env->NewObject(pointClass, pointConstructor, point.x, point.y);
env->CallBooleanMethod(arrayListObj, arrayListAddMethod, pointObj);
}
return arrayListObj;
}
}
Java代码:
package com.example;
import java.util.ArrayList;
public class MyClass {
static {
System.loadLibrary("mylib");
}
public native ArrayList<Point> getPoints();
public static void main(String[] args) {
MyClass myClass = new MyClass();
ArrayList<Point> points = myClass.getPoints();
for (Point point : points) {
System.out.println("x: " + point.x + ", y: " + point.y);
}
}
}
在这个示例中,C++代码定义了一个返回vector<Point>的函数getPoints()。JNI代码中的Java_com_example_MyClass_getPoints()函数是JNI函数,它调用了C++的getPoints()函数,并将返回的vector<Point>对象转换为Java的ArrayList对象。最后,Java代码调用getPoints()函数并打印结果。
请注意,这只是一个示例,实际应用中可能需要根据具体情况进行适当的修改和调整。
领取专属 10元无门槛券
手把手带您无忧上云