12.6.9 뷰(Views)
12.6.9 뷰(Views)
cpp.marshal.View 타입은 관리되거나 관리되지 않은 메모리의 연속 영역을 나타내는 데 사용할 수 있는 내장 스택 전용 값 타입 extern입니다. 스택 전용 타입이므로 GC 할당을 0으로 하여 메모리 작업을 위한 편리한 API를 제공하며, 안전한 접근과 원시 포인터 사용에 가까운 성능을 보장합니다.
표준 Haxe 타입에서 뷰를 만드는 편의 함수가 cpp.marshal.ViewExtensions 클래스에 있습니다. 예를 들어 haxe.ds.Vector에서 span을 만들 수 있습니다.
import cpp.marshal.View;
import haxe.ds.Vector;
using cpp.marshal.ViewExtensions;
using haxe.Int64;
function main() {
final source = new Vector<Int>(10);
final view = source.asView();
for (i in 0...view.length.toInt()) {
view[i] = i;
}
trace(source); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
}
같은 예는 최소한의 변경으로 네이티브 메모리에서도 작동할 수 있습니다.
import cpp.marshal.View;
using cpp.marshal.ViewExtensions;
using haxe.Int64;
function main() {
final source : cpp.Star<UInt8> = Native.malloc(10);
final view = Pointer.fromStar(source).asView(10);
for (i in 0...view.length.toInt()) {
view[i] = i;
}
trace(view.toArray()); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
}
슬라이스(Slices)
두 개의 slice 오버로드는 원래 뷰의 하위 영역을 가리키는 새 뷰를 반환합니다. 이 함수들은 추가 할당이나 인덱스와 길이를 수동으로 관리할 필요 없이 메모리 영역을 다루는 인체공학적인 방법을 제공합니다.
import cpp.marshal.View;
import haxe.ds.Vector;
using cpp.marshal.ViewExtensions;
using haxe.Int64;
function main() {
final source = new Vector<Int>(10);
final view = source.asView().slice(2, 5);
for (i in 0...view.length.toInt()) {
view[i] = 10 + i;
}
trace(source); // [ 0, 0, 10, 11, 12, 13, 14, 0, 0, 0 ]
}
재해석(Reinterpret)
뷰를 재해석하면 메모리 영역을 값 타입 extern을 포함한 다른 타입으로 취급할 수 있습니다. 다음 예는 바이트를 할당하고 이를 Point 값 타입 extern으로 재해석한 다음 그 x와 y 필드에 임의 값을 씁니다. cpp.marhal.View가 메모리 영역을 가리키므로 이러한 모든 쓰기는 원래 haxe.io.Bytes 객체에서 발생합니다.
import cpp.marshal.View;
import haxe.ds.Vector;
using cpp.marshal.ViewExtensions;
using haxe.Int64;
function main() {
final source = new Vector<Int>(10);
final view = source.asView().slice(2, 5);
for (i in 0...view.length.toInt()) {
view[i] = 10 + i;
}
trace(source); // [ 0, 0, 10, 11, 12, 13, 14, 0, 0, 0 ]
}
출처: Views