Skip to content
This repository has been archived by the owner on Jan 17, 2024. It is now read-only.

Runtime error for Pointer.fromFunction(). Not sure if error is valid. #227

Closed
thumbert opened this issue Dec 15, 2023 · 2 comments
Closed

Comments

@thumbert
Copy link

Hi,

I'm getting an error when it think I shouldn't.

See for example https://github.com/thumbert/gsl_dart/blob/main/example/minimization_example.dart line 9.

There are no analyzer errors in the project. When I run the file I get the error message:

$dart run example/minimization_example.dart 
lib/src/minimize.dart:27:46: Error: fromFunction expects a static function as parameter. dart:ffi only supports calling static Dart functions from native code. Closures and tear-offs are not supported because they can capture context.
    pFun.ref.function = Pointer.fromFunction(fn, 0.0);

How come Minimizer.fn = (x, params) => cos(x) + 1.0; is not a static function? If I hard code it directly in https://github.com/thumbert/gsl_dart/blob/main/lib/src/minimize.dart line 44, the program runs fine.

Thanks,
T

@dcharkes
Copy link
Contributor

fromFunction only accepts toplevel functions.

If you want to use closures, use NativeCallable instead.

For more info:

@thumbert
Copy link
Author

Thank you. I made it to work. I will continue to explore.

If I get to make good progress and clean up the code, this package may serve as another example of Dart to C bindings.

Minimizer({
    this.algorithm = MinimizeAlgorithm.brent,
    required double Function(double) fn,
    required num xLower,
    required num xUpper,
    required this.xInitial,
  }) {
    final Pointer<gsl_function_struct> pFun = calloc<gsl_function_struct>();
    pFun.ref.function =
        NativeCallable<Double Function(Double, Pointer<Void>)>.isolateLocal(
                (double x, Pointer<Void> parms) => fn(x),
                exceptionalReturn: 0.0)
            .nativeFunction;
    pFun.ref.params = Pointer.fromAddress(0);
   ...

Cheers,
T

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

2 participants