dart-archive / ffi

Utilities for working with Foreign Function Interface (FFI) code
https://pub.dev/packages/ffi
BSD 3-Clause "New" or "Revised" License
155 stars 32 forks source link

How to pass a Dart function to C? A GNU Scientific Library example. #226

Closed thumbert closed 12 months ago

thumbert commented 1 year ago

Hi,

I'm trying to make a Dart wrapper for GNU GSL. Unfortunately my C skills are not that strong, but I would like to learn my way into adding more functionality to Dart.

I have created a package gsl_dart where I've generated the C bindings and was able to call simple functions. I'm getting stuck on more complicated cases, for example this one dimensional minimization.

Can somebody help me translate this C example to Dart?

      var brent = gsl.gsl_min_fminimizer_brent;
      var solver = gsl.gsl_min_fminimizer_alloc(brent);

      var m = 2.0;
      var a = 0.0;
      var b = 6.0;
      fn1(double x) => cos(x) + 1.0;

      // final fMin = calloc.allocate<gsl_function_struct>();

      gsl.gsl_min_fminimizer_set(solver, ??, m, a, b);

I found a Python example of this code which looks great. Ideally, I would like the final Dart version to look similar -- I can wrap the calls into classes, etc. but I need to figure out the C calls first.

Thanks, T

dcharkes commented 1 year ago

Hey @thumbert, nice to meet you!

If it's a synchronous callback on the same thread, you can use NativeCallable.isolateLocal, see https://api.dart.dev/stable/3.2.2/dart-ffi/NativeCallable/NativeCallable.isolateLocal.html for documentation.

thumbert commented 12 months ago

Thanks. I made it to work.