I want to write dart binding for the following C code:
c api:
TFL_CAPI_EXPORT extern TfLiteQuantizationParams TfLiteTensorQuantizationParams(
const TfLiteTensor* tensor);
typedef struct TfLiteQuantizationParams {
float scale;
int32_t zero_point;
} TfLiteQuantizationParams;
I tried doing this:
dart binding:
TfLiteQuantizationParams Function(Pointer<TfLiteTensor> tensor)
TfLiteTensorQuantizationParams = tflitelib
.lookup<NativeFunction<_TfLiteTensorQuantizationParams_native_t>>(
'TfLiteTensorQuantizationParams')
.asFunction();
typedef _TfLiteTensorQuantizationParams_native_t
= TfLiteQuantizationParams Function(Pointer<TfLiteTensor> tensor);
But I am facing the following error;
Compiler message:
../lib/src/bindings/tensor.dart:126:6: Error: Expected type 'NativeFunction<TfLiteQuantizationParams Function(Pointer<TfLiteTensor>)>' to be a valid and instantiated subtype of 'NativeType'.
- 'NativeFunction' is from 'dart:ffi'.
- 'TfLiteQuantizationParams' is from 'package:tflite_flutter_plugin/src/bindings/types.dart' ('../lib/src/bindings/types.dart').
- 'Pointer' is from 'dart:ffi'.
- 'TfLiteTensor' is from 'package:tflite_flutter_plugin/src/bindings/types.dart' ('../lib/src/bindings/types.dart').
.asFunction();
dart struct
class TfLiteQuantizationParams extends Struct {
@Float()
double scale;
@Int32()
int zero_point;
@override
String toString() {
return 'TfLiteQuantizationParams{scale: $scale, zero_point: $zero_point}';
}
}
I need some help to get this working.
Thanks in advance
Related issue https://github.com/dart-lang/sdk/issues/36730. @dcharkes Can you suggest a workaround for my problem?
We do not support passing structs by value yet indeed (I'm working on it).
The workaround is to write some wrapper C code that turns it into a pointer.
Dart code:
final tfLiteTensorQuantizationParamsWrapped = tflitelib.lookupFunction<
Pointer<TfLiteQuantizationParams> Function(Pointer<TfLiteTensor> tensor),
Pointer<TfLiteQuantizationParams> Function(
Pointer<TfLiteTensor> tensor)>('TfLiteTensorQuantizationParams');
Closing issue as https://github.com/dart-lang/sdk/issues/36730, please reopen if you have any issues with the workaround in the mean time.
Most helpful comment
We do not support passing structs by value yet indeed (I'm working on it).
The workaround is to write some wrapper C code that turns it into a pointer.
Dart code: