[doc/ffi] Fix CString implementation in dart:ffi sample

Change-Id: I3dcb9fefe3d13f21da1c923dd69cc2a994ccf51e
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/103128
Auto-Submit: Daco Harkes <dacoharkes@google.com>
Reviewed-by: Vyacheslav Egorov <vegorov@google.com>
Commit-Queue: Daco Harkes <dacoharkes@google.com>
This commit is contained in:
Daco Harkes 2019-05-21 08:53:08 +00:00 committed by commit-bot@chromium.org
parent 7f67e83e36
commit e7f7984995
2 changed files with 7 additions and 7 deletions

View file

@ -71,19 +71,19 @@ class StatementPointer extends Pointer<Void> {}
Strings in C are pointers to character arrays.
```dart
class CString extends Pointer<Int8> {}
class CString extends Pointer<Uint8> {}
```
Pointers to C integers, floats, an doubles can be read from and written through to `dart:ffi`.
However, before we can write to C memory from dart, we need to `allocate` some memory.
```dart
Pointer<Int8> p = allocate(); // Infers type argument allocate<Int8>(), and allocates 1 byte.
p.store(123); // Stores a Dart int into this C int8.
int v = p.load(); // Infers type argument p.load<int>(), and loads a value from C memory.
Pointer<Uint8> p = allocate(); // Infers type argument allocate<Uint8>(), and allocates 1 byte.
p.store(123); // Stores a Dart int into this C int8.
int v = p.load(); // Infers type argument p.load<int>(), and loads a value from C memory.
```
Note that you can only load a Dart `int` from a C `Int8`.
Note that you can only load a Dart `int` from a C `Uint8`.
Trying to load a Dart `double` will result in a runtime exception.
We've almost modeled C Strings.

View file

@ -8,7 +8,7 @@ import "dart:ffi";
import "arena.dart";
/// Represents a String in C memory, managed by an [Arena].
class CString extends Pointer<Int8> {
class CString extends Pointer<Uint8> {
/// Allocates a [CString] in the current [Arena] and populates it with
/// [dartStr].
factory CString(String dartStr) => CString.inArena(Arena.current(), dartStr);
@ -23,7 +23,7 @@ class CString extends Pointer<Int8> {
/// memory manually!
factory CString.allocate(String dartStr) {
List<int> units = Utf8Encoder().convert(dartStr);
Pointer<Int8> str = allocate(count: units.length + 1);
Pointer<Uint8> str = allocate(count: units.length + 1);
for (int i = 0; i < units.length; ++i) {
str.elementAt(i).store(units[i]);
}