简体   繁体   English

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

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

How to call a native function with output parameter with Dart ffi, since dart doesn't support output parameters. 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我正在寻找类似 C# 代码的替代方案

[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)

I was able to do it by using malloc with zero length from package:ffi我能够通过使用malloc来做到这一点, package:ffi

final dbPointer = malloc.allocate<duckdb_database>(0);
print(dbPointer.value); // some initial value
db.open_ext(dbPointer);
print(dbPointer.value); // new value!!

Zero clue if this is "right", but it's working for me!如果这是“正确的”,零线索,但它对我有用!

// 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. Dart SDK 存储库中的SQLite 样本具有相同的模式,但没有参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM