当我try 在C++中获取 struct 返回值时,我无法解析 struct 中的值.
这就是我的 struct .
struct Point {
int x;
int y;
};
这是我的C++方法
Point test_point(Point points[],long count)
{
if (count <= 0) {
// Return a default Point with x and y set to 0
Point defaultPoint = { 0, 0 };
return defaultPoint;
}
Point maxPoint = points[0];
int maxSum = maxPoint.x + maxPoint.y;
for (int i = 1; i < count; ++i) {
int currentSum = points[i].x + points[i].y;
if (currentSum > maxSum) {
maxSum = currentSum;
maxPoint = points[i];
}
}
int x = maxPoint.x;
int y = maxPoint.y;
std::cout << "x = " << x << ", y = " << y << std::endl;
return maxPoint;
}
这是我的Java方法
public static void dereferenceSegmentsStruct() throws Throwable {
Linker linker = Linker.nativeLinker();
SymbolLookup symbolLookup = SymbolLookup.loaderLookup();
MethodHandle test_point = linker.downcallHandle(
symbolLookup.find("test_point").orElseThrow(),
FunctionDescriptor.of(ADDRESS, ADDRESS, JAVA_LONG)
);
StructLayout structLayout = MemoryLayout.structLayout(
JAVA_INT.withName("x"),
JAVA_INT.withName("y"));
SequenceLayout ptsLayout = MemoryLayout.sequenceLayout(10, structLayout);
VarHandle xHandle // (MemorySegment, long) -> int
= ptsLayout.varHandle(PathElement.sequenceElement(),
PathElement.groupElement("x"));
VarHandle yHandle // (MemorySegment, long) -> int
= ptsLayout.varHandle(PathElement.sequenceElement(),
PathElement.groupElement("y"));
MemorySegment segment = Arena.ofAuto().allocate(ptsLayout);
for (int i = 0; i < ptsLayout.elementCount(); i++) {
xHandle.set(segment,
/* index */ (long) i,
/* value to write */ i); // x
yHandle.set(segment,
/* index */ (long) i,
/* value to write */ i); // y
}
MemorySegment result = (MemorySegment) test_point.invoke(segment, ptsLayout.elementCount());
result = result.reinterpret(structLayout.byteSize());
System.out.println(result.getAtIndex(JAVA_INT, 0));
}
我看到零长度,我试着用一种方法来修改零长度.
我仍然不能得到它,它给出以下错误.
Exception in thread "main" java.lang.IllegalArgumentException: Misaligned access at address: 38654705673
at java.base/java.lang.invoke.VarHandleSegmentViewBase.newIllegalArgumentExceptionForMisalignedAccess(VarHandleSegmentViewBase.java:57)
at java.base/java.lang.invoke.VarHandleSegmentAsInts.offsetNoVMAlignCheck(VarHandleSegmentAsInts.java:100)
at java.base/java.lang.invoke.VarHandleSegmentAsInts.get(VarHandleSegmentAsInts.java:111)
at java.base/java.lang.foreign.MemorySegment.getAtIndex(MemorySegment.java:1921)
at org.example/org.example.TestNative.dereferenceSegmentsStruct(TestNative.java:109)
at org.example/org.example.TestNative.main(TestNative.java:33)
我需要做什么来读取在C++中返回的Point的x和y?