[vm/ffi] Fix FFI Utf8 example.

Change-Id: Ic6c93c94f1187595b0dab2c912ebf4851ac85fe5
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/108406
Reviewed-by: Daco Harkes <dacoharkes@google.com>
Commit-Queue: Samir Jindel <sjindel@google.com>
This commit is contained in:
Samir Jindel 2019-07-09 11:37:44 +00:00 committed by commit-bot@chromium.org
parent e3b3c6fa28
commit 7acecda2cc
5 changed files with 24 additions and 7 deletions

View file

@ -9,7 +9,7 @@ import "arena.dart";
/// Represents a String in C memory, managed by an [Arena].
class Utf8 extends Struct<Utf8> {
@Int8()
@Uint8()
int char;
/// Allocates a [CString] in the current [Arena] and populates it with

View file

@ -7,6 +7,7 @@
import "package:test/test.dart";
import '../lib/sqlite.dart';
import '../lib/src/ffi/utf8.dart';
void main() {
test("sqlite integration test", () {
@ -161,4 +162,10 @@ void main() {
r.close();
d.close();
});
test("Utf8 unit test", () {
final String test = 'Hasta Mañana';
final medium = Utf8.allocate(test);
expect(test, medium.load<Utf8>().toString());
medium.free();
});
}

View file

@ -12,7 +12,7 @@ import 'dart:ffi';
import "package:expect/expect.dart";
import 'cstring.dart';
import 'utf8.dart';
import 'dylib_utils.dart';
DynamicLibrary ffiTestFunctions = dlopenPlatformSpecific("ffi_test_functions");

View file

@ -12,6 +12,7 @@ import "package:expect/expect.dart";
import 'coordinate_bare.dart' as bare;
import 'coordinate.dart';
import 'utf8.dart';
void main() {
testStructAllocate();
@ -19,6 +20,7 @@ void main() {
testStructWithNulls();
testBareStruct();
testTypeTest();
testUtf8();
}
/// allocates each coordinate separately in c memory
@ -118,3 +120,10 @@ void testTypeTest() {
Expect.isTrue(c is Struct<Coordinate>);
c.addressOf.free();
}
void testUtf8() {
final String test = 'Hasta Mañana';
final Pointer<Utf8> medium = Utf8.toUtf8(test);
Expect.equals(test, Utf8.fromUtf8(medium));
medium.free();
}

View file

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library FfiTest;
library Utf8;
import 'dart:convert';
import 'dart:ffi' as ffi;
@ -10,7 +10,7 @@ import 'dart:ffi' show Pointer;
/// Sample non-struct Pointer wrapper for dart:ffi library.
class Utf8 extends ffi.Struct<Utf8> {
@ffi.Int8()
@ffi.Uint8()
int char;
static String fromUtf8(Pointer<Utf8> str) {
@ -25,12 +25,13 @@ class Utf8 extends ffi.Struct<Utf8> {
}
static Pointer<Utf8> toUtf8(String s) {
Pointer<Utf8> result = Pointer<Utf8>.allocate(count: s.length + 1).cast();
List<int> units = Utf8Encoder().convert(s);
for (int i = 0; i < s.length; i++) {
Pointer<Utf8> result =
Pointer<Utf8>.allocate(count: units.length + 1).cast();
for (int i = 0; i < units.length; i++) {
result.elementAt(i).load<Utf8>().char = units[i];
}
result.elementAt(s.length).load<Utf8>().char = 0;
result.elementAt(units.length).load<Utf8>().char = 0;
return result;
}
}