Skip to content

Latest commit

 

History

History
44 lines (32 loc) · 1.77 KB

File metadata and controls

44 lines (32 loc) · 1.77 KB

MemoryScope

MemoryScope abstracts the FFM API's Arena and SegmentAllocator. It is the primary way to allocate, manage, and release native memory segments in a structured block.

Key Features

  • Scoping: Implements AutoCloseable. Closing the scope instantly frees all allocations made within it.
  • Type-Safe Helpers: Directly allocate pointers, strings, and arrays without manually using ValueLayout descriptors.
  • Aligned with type mappers: allocateBoolean / allocateChar use the same 1-byte layouts as boolean / char downcalls (see NativeTypes.md).

Usage Example

import io.github.undeffineddev.ffmkit.memory.MemoryScope;
import io.github.undeffineddev.ffmkit.memory.Pointer;
import io.github.undeffineddev.ffmkit.memory.CString;
import io.github.undeffineddev.ffmkit.memory.NativeArray;

try (MemoryScope scope = MemoryScope.open()) {
    
    // Allocate a pointer to a single integer
    Pointer<Integer> intPtr = scope.allocateInt();
    intPtr.set(100);
    
    // Allocate a C string (UTF-8)
    CString text = scope.string("Panama");
    
    // Allocate a platform-native wchar_t* string
    WString wtext = scope.stringWide("Panama");
    
    // Allocate a raw MemorySegment for UTF-16
    java.lang.foreign.MemorySegment rawWtext = scope.allocateUtf16("Panama");
    
    // Allocate an array of primitive integers
    NativeArray<Integer> arr = scope.arrayOf(1, 2, 3);
    // Equivalent convenience factory:
    NativeArray<Integer> alsoArr = NativeArray.arrayOf(scope, 1, 2, 3);
    
    System.out.println(intPtr.get()); // 100
    System.out.println(text.toString()); // Panama
    System.out.println(wtext.toString()); // Panama
    System.out.println(arr.get(2)); // 30

} // All native memory allocated inside is freed here