Dart / Flutter ffi(Foreig函数接口)本机回调,例如:sqlite3_exec [英] Dart/Flutter ffi (Foreig Function Interface) native callbacks eg: sqlite3_exec
问题描述
您好,我正在使用dart:ffi与本机c / c ++库建立接口。
,我需要一种从c到dart进行回调的方法,例如在sqlite中:
Hello I am using dart:ffi to build an interface with my native c/c++ library. and I needed a way to get a callback from c to dart as an example in sqlite:
int sqlite3_exec(
sqlite3*, /* An open database */
const char *sql, /* SQL to be evaluated */
int (*callback)(void*,int,char**,char**), /* Callback function */
void *, /* 1st argument to callback */
char **errmsg /* Error msg written here */
);
sqlite3_exec
中的第三个参数是函数指针回调。
,因此,如果我使用 ffi
在dart中调用此函数,则需要传递一个函数指针:在 dart:ffi $ c中$ c>
Pointer
类中有一个名为 fromFunction
的函数,它接受dart静态函数和 exceptionalReturn
;但是只需调用此函数以获取dart托管函数的函数指针:就会产生(sigterm)
,并且dart代码在该过程中不再起作用。
the third parameter in sqlite3_exec
is function pointer to a callback.
so if I called this function in dart using ffi
I need to pass a function pointer: and in dart:ffi
Pointer
class there is a function named fromFunction
witch accepts a dart static function and an exceptionalReturn
; but just by calling this function to get the function pointer of a dart managed function: a (sigterm)
is raised and the dart code no long work in the process.
所以我的问题:有没有办法在dart中获得本机回调,如Python,c#,..
So My Question: Is there any way to get a native callback in dart, as in Python, c#, ..
额外:
是否可以在 flutter
项目中包含 dartino
,因为此 ForeignDartFunction 涵盖了我的需要。
Extra:
Is there any way to include dartino
in a flutter
project, since this ForeignDartFunction covers what I need.
推荐答案
我有一个工作示例。希望您可以根据情况进行调整。
I got an example to work. Hopefully you can adapt this to your case.
示例C函数
EXTERNC int32_t foo(
int32_t bar,
int32_t (*callback)(void*, int32_t)
) {
return callback(nullptr, bar);
}
飞镖代码
首先是 typedefs
。对于本地函数 foo
,我们需要两个,对于Dart回调,我们需要一个。
First the typedefs
. We need two for the native function foo
and one for the Dart callback.
typedef example_foo = Int32 Function(
Int32 bar, Pointer<NativeFunction<example_callback>>);
typedef ExampleFoo = int Function(
int bar, Pointer<NativeFunction<example_callback>>);
typedef example_callback = Int32 Function(Pointer<Void>, Int32);
以及回调代码
static int callback(Pointer<Void> ptr, int i) {
print('in callback i=$i');
return i + 1;
}
和查找
ExampleFoo nativeFoo =
nativeLib.lookup<NativeFunction<example_foo>>('foo').asFunction();
最后,像这样使用它:
int foo(int i) {
return nativeFoo(
i,
Pointer.fromFunction<example_callback>(callback, except),
);
}
如预期的那样, foo(123)
在回调i = 123 中显示 flutter:并返回
124
as expected, foo(123)
prints flutter: in callback i=123
and returns 124
这篇关于Dart / Flutter ffi(Foreig函数接口)本机回调,例如:sqlite3_exec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!