Skip to content

dart:ffi: Explain Struct wrapping or not #39808

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
derolf opened this issue Dec 16, 2019 · 3 comments
Closed

dart:ffi: Explain Struct wrapping or not #39808

derolf opened this issue Dec 16, 2019 · 3 comments
Labels
area-core-library SDK core library issues (core, async, ...); use area-vm or area-web for platform specific libraries. library-ffi

Comments

@derolf
Copy link

derolf commented Dec 16, 2019

From the documentation of Struct it is unclear whether loading a Struct from a Pointer actually creates a Dart Wrapper-Object or if it is an intrinsic “hack” without additionally allocation.

@vsmenon vsmenon added area-core-library SDK core library issues (core, async, ...); use area-vm or area-web for platform specific libraries. library-ffi labels Dec 18, 2019
@dcharkes
Copy link
Contributor

It's a Dart wrapper object.

It roughly looks like the following.

MyStruct extends Struct {  // View on C memory.
  Pointer<MyStruct> _hiddenPointer; // Pointer to C memory.

  // Accessors for C memory
  int get x => _hiddenPointer.cast<Int64>().value;
  set x(int newValue) => _hiddenPointer.cast<Int64>().value = newValue;

  int get y => _hiddenPointer.offsetInBytes(8).cast<Int64>().value;
  set y(int newValue) => _hiddenPointer.offsetInBytes(8).cast<Int64>().value = newValue;
}

However, note that when we will add support for structs by value (#36730), we actually need to store the data in Dart memory:

MyStruct extends Struct { // View on Dart or C memory.
  _SomePointer _data; // Pointer<MyStruct> extends _SomePointer and TypedData extends _SomePointer.

  // ...
}

@dcharkes
Copy link
Contributor

Note that when we implement the struct operation optimizations (#38648) the Dart optimizer might decide to not materialize the MyStruct object at all in the following code:

Pointer<MyStruct> p;
p.ref.x = 1;

The optimizer can turn this conceptually* into the following:

Pointer<MyStruct> p;
p.cast<Int64>().value = 1;

*The optimizer doesn't work on source code, but an intermediate representation. So showing an optimization on source code isn't fully accurate.

@Sunbreak
Copy link

A example: dart-lang/native#506

@derolf derolf closed this as completed Mar 15, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-core-library SDK core library issues (core, async, ...); use area-vm or area-web for platform specific libraries. library-ffi
Projects
None yet
Development

No branches or pull requests

4 participants