flutter dart中用ffi调用golang或C的动态链接库

news/2025/2/7 11:51:33/

本文介绍从dart中,通过ffi方式调用golang生成的动态链接库。

go/lib.go

package mainimport "C"//export GetKey
func GetKey() *C.char {theKey := "123-456-789"return C.CString(theKey)
}func main() {}
cd go
go build -buildmode=c-shared -o lib.a lib.go

如果是android上的arm64:

GOOS=android GOARCH=arm64 CGO_ENABLED=1 CC=/home/leon/app/lib/android-sdk/ndk/23.1.7779620/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android30-clang go build -buildmode=c-shared -o libgetkey.so lib.go
$ file libgetkey.so
libgetkey.so: ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked, Go BuildID=DcPg8Sp5h2rp3UWnE6Zg/_OH6HiVNpMa5Q-1cB2k6/9fkQff1HpM8_877p07S9/Dsh4z9riT9y9DVK5HiSQ, with debug_info, not stripped

然后创建lib/checkffi.dart文件。

lib/checkffi.dart

import 'dart:ffi';
import 'dart:io' show Directory, Platform;import 'package:ffi/ffi.dart';
import 'package:path/path.dart' as path;// C function: char *GetKey();
// There's no need for two typedefs here, as both the
// C and Dart functions have the same signature
typedef HelloWorld = Pointer<Utf8> Function();getKey() {// Open the dynamic libraryvar libraryPath =path.join(Directory.current.path, 'go', 'lib.a');final dylib = DynamicLibrary.open(libraryPath);final helloWorld =dylib.lookupFunction<HelloWorld, HelloWorld>('GetKey');final message = helloWorld().toDartString();return message;
}

如果想做个测试:

lib.dart

import 'fficheck.dart';main() {print("Hello, World!");print(getKey());
}
flutter main.dartimport 'package:flutter/material.dart';
import "fficheck.dart";void main() {runApp(const MyApp());
}class MyApp extends StatelessWidget {const MyApp({super.key});// This widget is the root of your application.Widget build(BuildContext context) {return MaterialApp(title: 'Flutter Demo',theme: ThemeData(// This is the theme of your application.//// Try running your application with "flutter run". You'll see the// application has a blue toolbar. Then, without quitting the app, try// changing the primarySwatch below to Colors.green and then invoke// "hot reload" (press "r" in the console where you ran "flutter run",// or simply save your changes to "hot reload" in a Flutter IDE).// Notice that the counter didn't reset back to zero; the application// is not restarted.primarySwatch: Colors.blue,),home: const MyHomePage(title: 'Flutter Demo Home Page'),);}
}class MyHomePage extends StatefulWidget {const MyHomePage({super.key, required this.title});// This widget is the home page of your application. It is stateful, meaning// that it has a State object (defined below) that contains fields that affect// how it looks.// This class is the configuration for the state. It holds the values (in this// case the title) provided by the parent (in this case the App widget) and// used by the build method of the State. Fields in a Widget subclass are// always marked "final".final String title;State<MyHomePage> createState() => _MyHomePageState();
}class _MyHomePageState extends State<MyHomePage> {int _counter = 0;void _incrementCounter() {setState(() {// This call to setState tells the Flutter framework that something has// changed in this State, which causes it to rerun the build method below// so that the display can reflect the updated values. If we changed// _counter without calling setState(), then the build method would not be// called again, and so nothing would appear to happen._counter++;});}Widget build(BuildContext context) {// This method is rerun every time setState is called, for instance as done// by the _incrementCounter method above.//// The Flutter framework has been optimized to make rerunning build methods// fast, so that you can just rebuild anything that needs updating rather// than having to individually change instances of widgets.return Scaffold(appBar: AppBar(// Here we take the value from the MyHomePage object that was created by// the App.build method, and use it to set our appbar title.title: Text(widget.title),),body: Center(// Center is a layout widget. It takes a single child and positions it// in the middle of the parent.child: Column(// Column is also a layout widget. It takes a list of children and// arranges them vertically. By default, it sizes itself to fit its// children horizontally, and tries to be as tall as its parent.//// Invoke "debug painting" (press "p" in the console, choose the// "Toggle Debug Paint" action from the Flutter Inspector in Android// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)// to see the wireframe for each widget.//// Column has various properties to control how it sizes itself and// how it positions its children. Here we use mainAxisAlignment to// center the children vertically; the main axis here is the vertical// axis because Columns are vertical (the cross axis would be// horizontal).mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[const Text('You have pushed the button this many times:',),Text(getKey(),style: Theme.of(context).textTheme.headlineMedium,),],),),floatingActionButton: FloatingActionButton(onPressed: _incrementCounter,tooltip: 'Increment',child: const Icon(Icons.add),), // This trailing comma makes auto-formatting nicer for build methods.);}
}

pubspec.yaml
中增加:

dependencies:
ffi: ^1.0.0

运行:
flutter pub get
然后启动运行。

在这里插入图片描述

如果是在android中:

1). 需要在android/app中创建CMakeList.txt:

cmake_minimum_required(VERSION 3.4.1)  # for exampleadd_library( getkeySHAREDIMPORTEDGLOBAL
)
set_target_properties(getkey PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libgetkey.so)

本文用src/main/jniLibs/arm64-v8a/目录。

2). 在 android/app/build.gradle中添加externalNativeBuild:

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

如果是C语言的源代码而不是so动态链接库,则CMakeList.txt内容参考如下:

cmake_minimum_required(VERSION 3.4.1)  # for exampleadd_library( getkey# Sets the library as a shared library.SHARED# Provides a relative path to your source file(s).src/main/c/getkey.c )

c源文件放在src/main/c/getkey.c里面

//
// Created by leon on 13/4/2023.
//
char* GetKey() {char* s = "123-456-789";return s;
}void main() {}

然后编译运行会自动生产不同架构版本的libgetkey.so,在flutter的build文件夹下面。

参考:
https://github.com/dart-lang/samples/tree/main/ffi
https://docs.flutter.dev/development/platform-integration/android/c-interop


http://www.ppmy.cn/news/44755.html

相关文章

【git】git的一些基础操作

文章目录一.git下载二.git初次操作1.生成公钥2.修改全局用户名和邮箱地址&#xff1a;3.本地仓库关联远端仓库4.本地初始化5.将项目上所有的文件添加到本地仓库6.提交到本地仓库7.创建main分支8.推送到main分支三.git其他操作1.develop分支2.查看分支3.切换分支4.查看分支历史一…

muduo源码剖析--Thread/EventLoopThread/EventLoopThreadPool

Thread类 muduo网络库的基础线程类&#xff0c;封装了线程的基本操作。 class Thread : noncopyable { public:using ThreadFunc std::function<void()>;explicit Thread(ThreadFunc, const std::string &name std::string());~Thread();void start(); //开启线…

Java实现图片验证码功能

文章目录一、背景二、实现步骤1、maven中加入依赖2、CaptchaController.java3、生成验证码配置4、CaptchaService.java接口5、CaptchaServiceImpl.java实现类6、增加验证码校验涉及文件一、背景 在实现登录功能时&#xff0c;为了防止特定的程序暴力破解&#xff0c;一般为了安…

ElasticSearch高级操作

一、批量操作 1、脚本形式 例&#xff1a; #删除5号 #新增8号 #更新2号 name为2号 POST _bulk {"delete":{"_index":"person1","_id":"5"}} {"create":{"_index":"person1","_id&quo…

负数的二进制表示

刚接触c语言的萌新可能对负数的二进制表示很蒙圈&#xff0c;-1不应该是10000001吗&#xff1f;为什么电脑上显示的都是11111111&#xff1f; 讨论这个话题之前我们要先了解原码&#xff0c;反码&#xff0c;补码的概念&#xff1a; 原码&#xff1a;带符号位的&#xff0c;其余…

F - Cow Contest

题目描述 Floyd 从老马的抽屉里发现了一张自驾地图&#xff0c;现在地图上有 N (1 ≤ N ≤ 100) 座城市&#xff0c;依次标号为 1, 2, ..., N&#xff0c; 城市之间由 M (1 ≤ M ≤ 4,500) 条单向边相连。给定输入的 M 条单向边后&#xff08;地图上保证没有自环且没有重复的单…

高等数学笔记(上下)

目录 不定积分定积分微分方程线性微分方程解的结构常系数齐次线性微分方程常系数齐次线性微分方程特解的求法 计算机解法 不定积分 第一类换元积分法&#xff1a;灵感来自于复合函数的求导&#xff0c;利用中间变量替换得到复合函数的积分法&#xff1a;设 f ( u ) f(u) f(u)具…

Mac远程控制工具有哪些

适用于Mac的远程控制工具有很多&#xff0c;这里我们给大家列举五个常用软件。 1、Apple Remote Desktop 苹果自带远程桌面正如其名称所承诺的那样。作为 Apple 出品的应用程序&#xff0c;您可以想象它的配置和上手是多么容易。从 App Store 下载 Apple Remote Desktop 后&a…