[Dart] dart:ffi NativeType 관련 정리 및 Pointer 사용법 (추후 추가)
아직 이것저것 실험해보는 중이라 부족할 수 있다.
Flutter 2.10.3, window10 64bit 환경에서 테스트.
1. int
inteager 관련은 종류가 많다.
- signed: Int8, Int16, Int32, Int64
- unsigned: Uint8, Uint16, Uint32, Uint64
ffi/native_type.dart 문서 내에 적힌 설명을 읽어보면, 뒤의 숫자는 각각 몇 bit짜리 정수(C 기준)에 해당하는지 알 수 있다. 테스트로 사용한 dll에서는 int형을 사용하였으므로, Int32로 테스트. bit 수 맞추지 않아도 오류는 나지 않는데...왠지 예상치 못한 동작이 있을 것 같으니 주의하는 편이 좋을 것 같다.
2. double, float, bool, void
얘네는 크게 어렵지 않다. 이름도 클래스라 대문자로 시작할 뿐이지, 똑같이 Double, Float, Bool, Void.
3. char
Utf8과 Utf16이 있다. Utf8은 char에, Utf16은 wchar_t에 대응하는 모양이다.
char*를 사용하고 싶다면 Pointer<Utf8>을 사용하라고 ffi/lib/src/utf8.dart에 친절하게 적혀 있다. Utf16의 경우에도 마찬가지. 다만 C++의 string class는 무엇을 사용해야 하는지 아직 찾지 못했다.
/// The contents of a native zero-terminated array of UTF-8 code units.
///
/// The Utf8 type itself has no functionality, it's only intended to be used
/// through a `Pointer<Utf8>` representing the entire array. This pointer is
/// the equivalent of a char pointer (`const char*`) in C code.
class Utf8 extends Opaque {}
4. 포인터
각종 포인터는 Pointer와 대응한다. 이와 관련한 이야기는 아래에 추가 후술.
메모리 할당 방법 때문에 삽질을 조금 했는데, malloc과 calloc이 구현되어 있었다. package:ffi/src/allocation.dart를 참고하자.
C/C++에서 사용하던 그 malloc 및 calloc과 비슷한 기능을 하고, 비슷한 차이점이 있다.
final Pointer<Int32> int_ptr = calloc.allocate(4);
final Pointer<Utf8> str_ptr = calloc.allocate(32);
이런식으로 할당해주면 된다.
5. Pointer class 값 할당
이거때문에 한참 찾아 헤멨는데...
- NativeType이 숫자(Int32, Double, etc...)일 경우: asTypedList를 이용해 해당 포인터에 대응하는 NativeType List로 바꿔준 후 fillRange 함수를 이용한다.
final Pointer<Int32> ptr = calloc.allocate(16); // malloc.allocate(4);
ptr.asTypedList(8).fillRange(0, 2, 10);
- NativeType이 문자(Utf8, Utf16)일 경우: fillRange가 제공되지 않는다! 대신 다른 방법을 찾았다. 아래와 같다. 물론 이 경우 final Pointer 형식의 사용이 불가능해진다.
Pointer<Utf8> char = calloc.allocate(32);
char = 'test'.toNativeUtf8();
아래처럼 initialize해도 가능하다.
final Pointer<Utf8> ptr = 'hello'.toNativeUtf8();
'Flutter' 카테고리의 다른 글
[Dart] flutter(dart)에서 dll 불러오기 (7) | 2022.03.24 |
---|---|
[Flutter] ipa build Xcode segmentfault 11 문제 (0) | 2022.03.22 |
[Flutter] ipa build 및 browser를 통한 ipa 설치 설정 방법 (0) | 2022.03.17 |
[Flutter] class operator override (0) | 2021.12.17 |
[Flutter] 현재 url 가져오기, 새 창으로 열기 (0) | 2021.12.13 |