Dart/Flutter FFI(Foreign Function Interface): calling a native function with output parameter using FFI in Dart

422
// Allocate some memory for the output to be written to.
final Pointer<Pointer<duckdb_database>> outDb = calloc<Pointer<duckdb_database>>();
// That memory contains a null pointer (we used calloc to zero the memory).
assert(outDb.value == nullptr);

// The native function should populate that memory.
db.open_ext(outDb);
assert(outDb.value != nullptr);

// Our native API probably wants a `duckdb_database*` in the rest of the API, so lets keep that variable.
final Pointer<duckdb_database> db = outDb.value;
// Don't forget to free the memory that we had for the out parameter.
calloc.free(outDb);

// Use `db`...

The SQLite sample in the Dart SDK repo has the same pattern with out parameters.

Share:
422
julemand101
Author by

julemand101

Professional programmer working on healthcare solutions in Denmark. In my spare time I really like programming on a lot of small projects primarily in Dart.

Updated on December 14, 2022

Comments

  • julemand101
    julemand101 over 1 year

    How to call a native function with output parameter with Dart ffi, since dart doesn't support output parameters. i am looking for an alternative for something like this C# Code

    [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
    
    String PrinterName="Printer1";
    IntPtr hPrinter = new IntPtr(0);
    OpenPrinter(PrinterName.Normalize(), out hPrinter, IntPtr.Zero)
    
    • frankenapps
      frankenapps almost 3 years
      Dart functions do not support out parameters. Because your function only has one out paramter, you could rewrite it to just return that pointer, if you have access to the native code...
    • Admin
      Admin almost 3 years
      thanks for replay. unfortunately i don't have access to native code (it is a windows driver file). is there any other workarounds to call such functions using ffi?
    • frankenapps
      frankenapps almost 3 years
      Well, you will probably have to write a wrapper library (probably in C++), that will export a C function that will then call the driver library and then return the pointer. But it feels like an ugly solution and there might be better options...