c - 使用 Flutter 中的位图数据调用 C 函数
问题描述
我的任务是使用相机拍照,将像素发送到 C 函数,并在函数返回有问题图像的指示时向用户提供消息(例如:对焦不佳、图片太暗等)。
我想调用一个 C 函数并向包含像素(以及图像宽度/高度等其他参数)的函数发送一个指针。这个想法是使用 C 代码并检查图像质量。
C 代码已准备就绪。我找到了如何将其绑定到 Flutter 中的示例。但我不知道如何获取位图数据和像素并将它们发送到 C 函数。
解决方案
您可以使用 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
推荐阅读
- sql - 我想在第一行相同但后来不同的 SQL 服务器中订购
- javascript - 正确处理嵌套的 Promise 拒绝
- amazon-web-services - AWS Step Functions:新的 startExecution.sync:2
无权创建托管规则 - spring-boot - 如何为@FeignClient 正确配置回退和重试器?
- geoserver - 从 DEM 计算挖方和填方体积
- azure-cosmosdb - 根据用户在 Blazor Web 程序集项目中的位置分配 CosmosClientOptions.ApplicationRegion
- node.js - 无法安装 yeoman,因为“找不到 'yo' 二进制文件。确保它已安装并在您的 $PATH 中”
- linux - 为什么即使文件存在,rhel8 aws systemd 服务也会抛出 No such file or directory 错误?
- amazon-web-services - 我想询问 AWS 数据传输费用
- java - 如何从json中删除元素,同时使用java从xml解析