Skip to content

Commit 9eb61ae

Browse files
[ffigen] Support passing C++ classes by value (dart-lang#3603)
1 parent 541121b commit 9eb61ae

8 files changed

Lines changed: 133 additions & 51 deletions

File tree

‎pkgs/ffigen/lib/src/code_generator/cpp_class.dart‎

Lines changed: 46 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -417,8 +417,13 @@ class $name implements $implementsClause {
417417
@override
418418
String? toCppBindingString(Writer w) {
419419
final context = w.context;
420-
String paramDecl(Parameter p) =>
421-
p.type.getNativeType(context, varName: p.name).trim();
420+
String paramDecl(Parameter p) {
421+
final baseType = p.type.typealiasType;
422+
if (baseType is CppClass) {
423+
return '${baseType.originalName}* ${p.name}';
424+
}
425+
return p.type.getNativeType(context, varName: p.name).trim();
426+
}
422427

423428
final deleteWrapper =
424429
'''
@@ -441,20 +446,27 @@ FFIGEN_EXPORT void ${name}_delete($originalName* self) {
441446
params = method.parameters.map(paramDecl).join(', ');
442447
body = 'return new $originalName($callArgs);';
443448
} else {
444-
final nativeType = method.returnType.getNativeType(context);
445-
returnTypeString = nativeType.trim();
449+
final returnBaseType = method.returnType.typealiasType;
450+
final isByValueReturn = returnBaseType is CppClass;
451+
452+
if (isByValueReturn) {
453+
returnTypeString = '${returnBaseType.originalName}*';
454+
} else {
455+
final nativeType = method.returnType.getNativeType(context);
456+
returnTypeString = nativeType.trim();
457+
}
458+
446459
final needsReturn = method.returnType != voidType;
447460
final returnPrefix = needsReturn ? 'return ' : '';
448461

449462
final otherParams = method.parameters.map(paramDecl);
450463

464+
final String callExpr;
451465
if (method.isStatic) {
452466
final targetType =
453467
method.originatingClass?.originalName ?? originalName;
454468
params = otherParams.join(', ');
455-
body =
456-
'$returnPrefix$targetType::'
457-
'${method.originalName}($callArgs);';
469+
callExpr = '$targetType::${method.originalName}($callArgs)';
458470
} else {
459471
final constPrefix = method.isConstant ? 'const ' : '';
460472
final selfType = '$constPrefix$originalName';
@@ -463,7 +475,13 @@ FFIGEN_EXPORT void ${name}_delete($originalName* self) {
463475
final suffix = method.returnType is CppUniquePtrType
464476
? '.release()'
465477
: '';
466-
body = '${returnPrefix}self->$methodName($callArgs)$suffix;';
478+
callExpr = 'self->$methodName($callArgs)$suffix';
479+
}
480+
481+
if (isByValueReturn) {
482+
body = 'return new ${returnBaseType.originalName}($callExpr);';
483+
} else {
484+
body = '$returnPrefix$callExpr;';
467485
}
468486
}
469487

@@ -478,7 +496,24 @@ FFIGEN_EXPORT $returnTypeString $symbol($params) {
478496
}
479497

480498
@override
481-
String getCType(Context context) => name;
499+
String getDartType(Context context) => name;
500+
501+
@override
502+
String getCType(Context context) {
503+
final ffi = context.libs.prefix(ffiImport);
504+
return '$ffi.Pointer<$ffi.Void>';
505+
}
506+
507+
@override
508+
String getFfiDartType(Context context) => getCType(context);
509+
510+
@override
511+
String convertFfiDartTypeToDartType(
512+
Context context,
513+
String value, {
514+
required bool objCRetain,
515+
String? objCEnclosingClass,
516+
}) => '$name.fromPointer($value, takeOwnership: true)';
482517

483518
@override
484519
String getNativeType(Context context, {String varName = ''}) =>
@@ -510,6 +545,8 @@ String _cppCallArg(Parameter p) {
510545
if (type is CppUniquePtrType) {
511546
final className = type.cppClass.originalName;
512547
return 'std::unique_ptr<$className>(${p.name})';
548+
} else if (type.typealiasType is CppClass) {
549+
return '*${p.name}';
513550
}
514551
return p.name;
515552
}

‎pkgs/ffigen/lib/src/header_parser/sub_parsers/classdecl_parser.dart‎

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -147,14 +147,6 @@ void _parseAnyMethod(
147147
);
148148
return;
149149
}
150-
if (parameters.any((p) => p.type.typealiasType is CppClass)) {
151-
// TODO(https://github.com/dart-lang/native/issues/3603)
152-
logger.fine(
153-
' ---- Skipping method $methodName, passing a C++ class by value is '
154-
'not currently supported',
155-
);
156-
return;
157-
}
158150

159151
final returnType = clang
160152
.clang_getCursorResultType(cursor)
@@ -169,13 +161,6 @@ void _parseAnyMethod(
169161
' ---- Skipping method $methodName, incomplete struct returned by value',
170162
);
171163
return;
172-
} else if (returnType.typealiasType is CppClass) {
173-
// TODO(https://github.com/dart-lang/native/issues/3603)
174-
logger.fine(
175-
' ---- Skipping method $methodName, returning a C++ class by value is '
176-
'not currently supported',
177-
);
178-
return;
179164
}
180165

181166
final className = classDecl.originalName;

‎pkgs/ffigen/test/header_parser_tests/cpp_unsupported_return_type_test.dart‎

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -82,24 +82,22 @@ void main() {
8282
reason: 'a forward-declared class cannot be returned by value',
8383
);
8484

85-
// Unsupported today: bindable in principle (a reference is ABI-wise a
86-
// pointer; a defined class could be heap-copied by the glue code). If
87-
// support is ever added, move these up to the bindable group with real
88-
// signature expectations instead of relaxing the checks.
8985
expect(
9086
methodNames,
91-
isNot(contains('badRef')),
92-
reason: 'a C++ reference return type has no Dart mapping',
87+
contains('badSelfByValue'),
88+
reason: 'a defined class returned by value is supported',
9389
);
90+
91+
// Unsupported today: references have no Dart mapping.
9492
expect(
9593
methodNames,
96-
isNot(contains('badConstRef')),
94+
isNot(contains('badRef')),
9795
reason: 'a C++ reference return type has no Dart mapping',
9896
);
9997
expect(
10098
methodNames,
101-
isNot(contains('badSelfByValue')),
102-
reason: 'a defined class returned by value is not supported',
99+
isNot(contains('badConstRef')),
100+
reason: 'a C++ reference return type has no Dart mapping',
103101
);
104102
});
105103

@@ -116,6 +114,11 @@ void main() {
116114
'primitives and pointers (even to an incomplete compound or a '
117115
'C++ class) are bindable parameter types',
118116
);
117+
expect(
118+
methodNames,
119+
contains('badSelfParam'),
120+
reason: 'a defined class passed by value is supported',
121+
);
119122

120123
// Never bindable: a parameter whose type has no definition anywhere in
121124
// the translation unit cannot be passed by value (C++ itself cannot
@@ -137,9 +140,7 @@ void main() {
137140
reason: 'a forward-declared class cannot be passed by value',
138141
);
139142

140-
// Unsupported today: bindable in principle, see the equivalent return
141-
// type group above. If support is ever added, move these up to the
142-
// bindable group with real signature expectations.
143+
// Unsupported today: references have no Dart mapping.
143144
expect(
144145
methodNames,
145146
isNot(contains('badRefParam')),
@@ -150,11 +151,6 @@ void main() {
150151
isNot(contains('badConstRefParam')),
151152
reason: 'a C++ reference parameter has no Dart mapping',
152153
);
153-
expect(
154-
methodNames,
155-
isNot(contains('badSelfParam')),
156-
reason: 'a defined class passed by value is not supported',
157-
);
158154

159155
// The copy constructor takes a C++ reference, so only the default
160156
// constructor survives.
@@ -174,22 +170,21 @@ void main() {
174170
expect(output, contains('Widget_self'));
175171
expect(output, contains('Widget_blobPtr'));
176172
expect(output, contains('Widget_goodParams'));
177-
// See the grouping in the return type test: the first three can never be
178-
// supported; the last three pin behavior that a future version may
179-
// relax, and should then move to positive expectations above.
173+
expect(output, contains('Widget_badSelfByValue'));
174+
expect(output, contains('Widget_badSelfParam'));
175+
176+
// Unsupported returns:
180177
expect(output, isNot(contains('badUnionByValue')));
181178
expect(output, isNot(contains('badAliasByValue')));
182179
expect(output, isNot(contains('badClassByValue')));
183180
expect(output, isNot(contains('badRef')));
184181
expect(output, isNot(contains('badConstRef')));
185-
expect(output, isNot(contains('badSelfByValue')));
186-
// Same for the unsupported parameter types (badRefParam and
187-
// badConstRefParam are covered by the badRef/badConstRef prefix checks
188-
// above).
182+
183+
// Unsupported parameters:
189184
expect(output, isNot(contains('badUnionParam')));
190185
expect(output, isNot(contains('badAliasParam')));
191186
expect(output, isNot(contains('badClassParam')));
192-
expect(output, isNot(contains('badSelfParam')));
187+
193188
// With its only use dropped, the forward-declared class must not leave
194189
// a wrapper class behind in the bindings.
195190
expect(output, isNot(contains('class Incomplete')));

‎pkgs/ffigen/test/native_cpp_test/cpp_class_test.cpp‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,20 @@ void Animal::Animal_delete() {}
2020

2121
bool Animal::isMammalClass() const { return true; }
2222

23-
double Animal::getWeight(double multiplier) const { return age * 1.5 * multiplier; }
23+
double Animal::getWeight(double multiplier) const {
24+
return age * 1.5 * multiplier;
25+
}
2426

25-
int Animal::addAges(int otherAge, float scale) { return (age + otherAge) * scale; }
27+
int Animal::addAges(int otherAge, float scale) {
28+
return (age + otherAge) * scale;
29+
}
2630

2731
int Animal::sum(int a, int b) { return a + b; }
2832

33+
Animal Animal::copyAndAddAge(Animal other) const {
34+
return Animal(age + other.age);
35+
}
36+
37+
bool Animal::haveSameAge(Animal a, Animal b) {
38+
return a.age == b.age;
39+
}

‎pkgs/ffigen/test/native_cpp_test/cpp_class_test.dart‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,19 @@ void main() {
4848
animal.dispose();
4949
});
5050

51+
test('Animal pass and return by value', () {
52+
final dog = Animal(10);
53+
final cat = Animal(20);
54+
55+
final combined = dog.copyAndAddAge(cat);
56+
expect(combined.getAge(), 30);
57+
expect(Animal.haveSameAge(dog, cat), isFalse);
58+
59+
combined.dispose();
60+
dog.dispose();
61+
cat.dispose();
62+
});
63+
5164
@pragma('vm:never-inline')
5265
void gcTestSubjectInner(Pointer<Int32> counter) {
5366
final _ = FinalizerTestSubject(counter.cast());

‎pkgs/ffigen/test/native_cpp_test/cpp_class_test.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,6 @@ class Animal {
1717
double getWeight(double multiplier) const;
1818
int addAges(int otherAge, float scale);
1919
static int sum(int a, int b);
20+
Animal copyAndAddAge(Animal other) const;
21+
static bool haveSameAge(Animal a, Animal b);
2022
};

‎pkgs/ffigen/test/native_cpp_test/cpp_class_test_bindings.dart‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,21 @@ class Animal implements ffi.Finalizable {
160160
return _Animal_sum(a, b);
161161
}
162162

163+
Animal copyAndAddAge(Animal other) {
164+
if (_ptr == ffi.nullptr) {
165+
throw StateError('This object has already been disposed.');
166+
}
167+
168+
return Animal.fromPointer(
169+
_Animal_copyAndAddAge(_ptr, other._ptr),
170+
takeOwnership: true,
171+
);
172+
}
173+
174+
static bool haveSameAge(Animal a, Animal b) {
175+
return _Animal_haveSameAge(a._ptr, b._ptr);
176+
}
177+
163178
void dispose() {
164179
if (_ptr == ffi.nullptr) {
165180
throw StateError('This object has already been disposed.');
@@ -223,6 +238,22 @@ external int _Animal_addAges(
223238
@ffi.Native<ffi.Int Function(ffi.Int, ffi.Int)>(symbol: 'Animal_sum')
224239
external int _Animal_sum(int a, int b);
225240

241+
@ffi.Native<
242+
ffi.Pointer<ffi.Void> Function(ffi.Pointer<ffi.Void>, ffi.Pointer<ffi.Void>)
243+
>(symbol: 'Animal_copyAndAddAge')
244+
external ffi.Pointer<ffi.Void> _Animal_copyAndAddAge(
245+
ffi.Pointer<ffi.Void> self,
246+
ffi.Pointer<ffi.Void> other,
247+
);
248+
249+
@ffi.Native<ffi.Bool Function(ffi.Pointer<ffi.Void>, ffi.Pointer<ffi.Void>)>(
250+
symbol: 'Animal_haveSameAge',
251+
)
252+
external bool _Animal_haveSameAge(
253+
ffi.Pointer<ffi.Void> a,
254+
ffi.Pointer<ffi.Void> b,
255+
);
256+
226257
@ffi.Native<ffi.Void Function(ffi.Pointer<ffi.Void>)>(symbol: 'Animal_delete')
227258
external void _Animal_delete(ffi.Pointer<ffi.Void> self);
228259

‎pkgs/ffigen/test/native_cpp_test/cpp_class_test_bindings.dart.cpp‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,14 @@ FFIGEN_EXPORT int Animal_sum(int a, int b) {
5050
return Animal::sum(a, b);
5151
}
5252

53+
FFIGEN_EXPORT Animal* Animal_copyAndAddAge(const Animal* self, Animal* other) {
54+
return new Animal(self->copyAndAddAge(*other));
55+
}
56+
57+
FFIGEN_EXPORT bool Animal_haveSameAge(Animal* a, Animal* b) {
58+
return Animal::haveSameAge(*a, *b);
59+
}
60+
5361
FFIGEN_EXPORT void Animal_delete(Animal* self) {
5462
delete self;
5563
}

0 commit comments

Comments
 (0)