【问题标题】:How to call a native C function from Flutter?如何从 Flutter 调用原生 C 函数?
【发布时间】:2021-08-19 21:38:15
【问题描述】:

我想从 Flutter 中调用 'hello_world' 函数。

    #include <stdio.h>
#include "hello.h"
__attribute__((visibility("default"))) __attribute__((used))
int main()
{
    hello_world();
    return 0;
}
void hello_world()
{
    printf("Hello World\n");
}

我在我的 plugin.dart 中尝试过这种方式:

final DynamicLibrary helloLib = Platform.isAndroid
    ? DynamicLibrary.open("libhello.so")
    : DynamicLibrary.process();

final void Function() hello =
helloLib
    .lookup<NativeFunction<Void Function()>>("hello_world")
    .asFunction();

在我的 main.dart 文件中,我尝试过这种方式:

body: Center(
          child: Text('Running on: ${hello}'),

但它显示 void 而不是显示结果。如何解决这个问题呢? 提前致谢。

【问题讨论】:

  • 邮政编码,而不是编码图片
  • 你的 C 代码出现在程序中(有一个main())。我认为您需要一个动态库。

标签: c flutter dart interop


【解决方案1】:

要在 Flutter 程序中使用 C 代码,请使用 dart:ffi 库(目前处于测试阶段)。

第 1 步:创建插件

第 2 步:添加 C/C++ 源代码

第 3 步:使用 FFI 库加载代码

你可以参考这个:https://docs.flutter.dev/development/platform-integration/c-interop

【讨论】:

    猜你喜欢
    • 2021-09-15
    • 2021-11-21
    • 2021-12-28
    • 2020-03-03
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    相关资源
    最近更新 更多