如何在Flutter中调用原生C语言编写的hello_world函数?
问题原因
- 你没有实际执行
hello函数,仅将函数对象本身插值到字符串中输出:hello的类型是void Function(),直接转为字符串的结果就是void - 你当前的C语言
hello_world函数无返回值,仅向控制台打印内容,该输出不会传递到Flutter层,就算调用函数也无法拿到可在界面显示的文本内容
解决方案
步骤1:修改C语言代码,调整函数返回值
将hello_world函数改为返回C字符串常量,无需使用printf,修改后重新编译生成动态库:
#include <stdio.h> #include "hello.h" __attribute__((visibility("default"))) __attribute__((used)) const char* hello_world() { return "Hello World"; }
步骤2:修改Dart层函数签名适配返回值
首先确保导入ffi相关依赖:
import 'dart:ffi'; import 'dart:io'; import 'package:ffi/ffi.dart';
提示:如果项目中没有添加ffi依赖,需要在pubspec.yaml的dependencies下添加
ffi: ^2.0.1(版本可根据实际情况调整)后执行flutter pub get。
修改动态库函数查找逻辑,匹配新的返回值类型:
final DynamicLibrary helloLib = Platform.isAndroid ? DynamicLibrary.open("libhello.so") : DynamicLibrary.process(); final Pointer<Utf8> Function() hello = helloLib .lookup<NativeFunction<Pointer<Utf8> Function()>>("hello_world") .asFunction();
步骤3:调整界面调用逻辑,正确执行函数并转码
在main.dart中先调用函数获取C字符串指针,再转为Dart字符串用于显示:
body: Center( child: Text('Running on: ${hello().toDartString()}'), )
如果仅需要验证函数调用是否成功,不需要界面显示返回值,也可以保留原来的void返回类型,在调用hello()后手动给Text组件赋值固定文本即可。
内容的提问来源于stack exchange,提问作者Neu Trino
相关产品推荐
相关产品推荐

