Skip to content

Commit 7ebccdd

Browse files
committed
add another test that uses MemorySegment to pass an array copy to Swift (ffm)
1 parent 2e1c8d8 commit 7ebccdd

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

Samples/SwiftJavaExtractFFMSampleApp/Sources/MySwiftLibrary/MySwiftLibrary.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,24 @@ public func withBuffer(body: (UnsafeRawBufferPointer) -> Void) {
6363
body(globalBuffer)
6464
}
6565

66+
public func getArray() -> [UInt8] {
67+
return [1, 2, 3]
68+
}
69+
70+
public func sumAllByteArrayElements(actuallyAnArray: UnsafeRawPointer, count: Int) -> Int {
71+
let bufferPointer = UnsafeRawBufferPointer(start: actuallyAnArray, count: count)
72+
let array = Array(bufferPointer)
73+
return Int(array.reduce(0, { partialResult, element in partialResult + element }))
74+
}
75+
76+
public func sumAllByteArrayElements(array: [UInt8]) -> Int {
77+
return Int(array.reduce(0, { partialResult, element in partialResult + element }))
78+
}
79+
80+
public func withArray(body: ([UInt8]) -> Void) {
81+
body([1, 2, 3])
82+
}
83+
6684
public func globalReceiveSomeDataProtocol(data: some DataProtocol) -> Int {
6785
p(Array(data).description)
6886
return data.count

Samples/SwiftJavaExtractFFMSampleApp/src/test/java/com/example/swift/WithBufferTest.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@
2020

2121
import static org.junit.jupiter.api.Assertions.*;
2222

23+
import java.lang.foreign.ValueLayout;
24+
import java.util.Arrays;
2325
import java.util.concurrent.atomic.AtomicLong;
26+
import java.util.stream.IntStream;
2427

2528
public class WithBufferTest {
2629
@Test
@@ -33,4 +36,25 @@ void test_withBuffer() {
3336

3437
assertEquals(124, bufferSize.get());
3538
}
39+
40+
@Test
41+
void test_sumAllByteArrayElements_throughMemorySegment() {
42+
byte[] bytes = new byte[124];
43+
Arrays.fill(bytes, (byte) 1);
44+
45+
try (var arena = AllocatingSwiftArena.ofConfined()) {
46+
// NOTE: We cannot use MemorySegment.ofArray because that creates a HEAP backed segment and therefore cannot pass into native:
47+
// java.lang.IllegalArgumentException: Heap segment not allowed: MemorySegment{ kind: heap, heapBase: [B@5b6ec132, address: 0x0, byteSize: 124 }
48+
// MemorySegment bytesSegment = MemorySegment.ofArray(bytes); // NO COPY (!)
49+
// MySwiftLibrary.sumAllByteArrayElements(bytesSegment, bytes.length);
50+
51+
var bytesCopy = arena.allocateFrom(ValueLayout.JAVA_BYTE, bytes);
52+
var swiftSideSum = MySwiftLibrary.sumAllByteArrayElements(bytesCopy, bytes.length);
53+
54+
System.out.println("swiftSideSum = " + swiftSideSum);
55+
56+
int javaSideSum = IntStream.range(0, bytes.length).map(i -> bytes[i]).sum();
57+
assertEquals(javaSideSum, swiftSideSum);
58+
}
59+
}
3660
}

0 commit comments

Comments
 (0)