This code snippet defines a generic function that has a type parameter T extends NativeType. Then T is used to define a C function signature to look up symbols from a dynamic library.
import 'dart:ffi';
lookupGeneric<T extends NativeType>() {
final dylib = DynamicLibrary.open("path");
final address = dylib.lookup<NativeFunction<Void Function(Pointer<T>)>>("Name");
final function = address.asFunction<void Function(Pointer<T>)>(isLeaf: false);
return (address, function);
}
void main() {
final func = lookupGeneric<Int8>();
}
My issue is that this code fails to compile with the following message:
Can't invoke 'asFunction' because the function signature 'NativeFunction<Void Function(Pointer<T>)>' for the pointer isn't a valid C function signature.
When I replace T for plain NativeType, it compiles without errors:
import 'dart:ffi';
lookupGeneric<T extends NativeType>() {
final dylib = DynamicLibrary.open("path");
// -> CHANGE HERE ˇˇˇˇˇˇˇˇˇˇ
final address = dylib.lookup<NativeFunction<Void Function(Pointer<NativeType>)>>("Name");
final function = address.asFunction<void Function(Pointer<T>)>(isLeaf: false);
return (address, function);
}
void main() {
final func = lookupGeneric<Int8>();
}
I don't, however, find this a satisfactory solution, and it also doesn't work when T is not used as a pointer.
Can someone explain why NativeType works but T extends NativeType doesn't? What would be the solution to use generic types in dart:ffi?