Struct와 Union의 하위 클래스는 생성자로 만들 수 없어요

Struct와 Union의 하위 클래스는 생성자로 만들 수 없어요

StructUnion의 하위 클래스를 생성 생성자(generative constructor)로 인스턴스화하려고 할 때 분석기가 이 진단을 띄워줘요. 이 클래스들은 네이티브 메모리에 바탕을 두고 있어서 그런 식으로 만들 수 없어요.

출처: Subclasses of Struct and Union are backed by native memory, and can't be instantiated by a generative constructor

본문

StructUnion의 하위 클래스를 생성 생성자로 인스턴스화하려고 하면 분석기가 이 진단을 만들어요. StructUnion은 네이티브 메모리에 바탕을 둔 클래스라서, 일반 생성자로는 만들 수 없어요.

FFI에 대해 더 알고 싶다면 C interop using dart:ffi 문서를 참고하세요.

다음 코드는 클래스 C를 생성 생성자로 인스턴스화하고 있어서 이 진단이 나와요.

import 'dart:ffi';

final class C extends Struct {
  @Int32()
  external int a;
}

void f() {
  C();
}

고치는 방법

클래스가 나타내는 구조체를 할당해야 한다면, ffi 패키지를 사용하면 돼요.

import 'dart:ffi';

import 'package:ffi/ffi.dart';

final class C extends Struct {
  @Int32()
  external int a;
}

void f() {
  final pointer = calloc.allocate<C>(4);
  final c = pointer.ref;
  print(c);
  calloc.free(pointer);
}

더 알아보기