dart-lang / dart-lang/native

Access Uint8List as a Struct

Open
#926 3 comments 1 reaction 0 assignees View on GitHub
package:ffi
Dominant language
Dart
Stars
275
Forks
144
Avg merge
2d 10h
Merged PRs (30d)
47

Description

Apologies if this is somehow self-evident (or if this is not the appropriate place to ask such questions), but I could not find a single example that demonstrates this.

I have received a UDP datagram from a desktop C++ application that corresponds to the following C struct:

```C
struct Packet
{
int magic;
int sender;
int action;
int payload_size;
uint8_t payload[1];
}
```

I have defined a Struct to mirror it in Dart:

```Dart
final class Packet extends Struct {
@Int32()
external int magic;

@Int32()
external int sender;

@Int32()
external int action;

@Int32()
external int payload_size;

external Pointer payload;
}
```

Can I cast the Uint8List datagram binary data into an instance of this Struct (e.g., `Pointer`)? Or should I instead be using more primitive functions that crawl offsets, like:

```Dart
var buffer = new Uint8List(8).buffer;
var bytes = new ByteData.view(buffer);
bytes.getUint16(offset);
```

Thanks in advance for any assistance.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.