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.
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, 2022Comments
-
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 almost 3 yearsDart 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 almost 3 yearsthanks 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 almost 3 yearsWell, 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...
-