首页 > 解决方案 > 使用 Flutter 中的位图数据调用 C 函数

问题描述

我的任务是使用相机拍照,将像素发送到 C 函数,并在函数返回有问题图像的指示时向用户提供消息(例如:对焦不佳、图片太暗等)。

我想调用一个 C 函数并向包含像素(以及图像宽度/高度等其他参数)的函数发送一个指针。这个想法是使用 C 代码并检查图像质量。

C 代码已准备就绪。我找到了如何将其绑定到 Flutter 中的示例。但我不知道如何获取位图数据和像素并将它们发送到 C 函数。

标签: cflutterimage-processingcamera

解决方案


您可以使用 dart:ffi 绑定到本机代码。

想象一下,您有一个 C 函数,它使用以下代码返回两个数字的总和:

#include <stdint.h>

extern "C" __attribute__((visibility("default"))) __attribute__((used))
int32_t native_add(int32_t x, int32_t y) {
    return x + y;
}

而这个 C Makefile

cmake_minimum_required(VERSION 3.4.1)  # for example

add_library( native_add

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             ../native_add.cpp )

现在你需要把这个 CMake 文件封装到 externalNativeBuild 里面build.gradle,这可以是一个例子:

android {
  // ...
  externalNativeBuild {
    // Encapsulates your CMake build configurations.
    cmake {
      // Provides a relative path to your CMake build script.
      path "CMakeLists.txt"
    }
  }
  // ...
}

现在您有了库并且封装了代码,您可以使用 FFI 库加载代码,如下所示:

import 'dart:ffi'; // For FFI
import 'dart:io'; // For Platform.isX

final DynamicLibrary nativeAddLib = Platform.isAndroid
    ? DynamicLibrary.open("libnative_add.so")
    : DynamicLibrary.process();

通过一个封闭库的句柄,您可以像我们在这里所做的那样解析 native_add 符号:

final int Function(int x, int y) nativeAdd =
  nativeAddLib
    .lookup<NativeFunction<Int32 Function(Int32, Int32)>>("native_add")
    .asFunction();

现在您可以在调用 nativeAdd 函数的应用程序上使用它,这里有一个示例:

body: Center(
    child: Text('1 + 2 == ${nativeAdd(1, 2)}'),
),

您可以在以下 url 中了解 Flutter 本机代码绑定的工作原理:flutter docs c-interop


推荐阅读