Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

ffi

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)
like image 362
Taju Rahman Avatar asked Feb 19 '26 13:02

Taju Rahman


1 Answers

// 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.

like image 158
Daco Harkes Avatar answered Feb 22 '26 14:02

Daco Harkes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!