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

news2024/9/24 15:25:57

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

go/lib.go

package main

import "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 library
  var 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.dart

import '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 example

add_library( getkey
        SHARED
        IMPORTED
        GLOBAL
)
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 example

add_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.coloradmin.cn/o/430880.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

高通QSSI方式导致CI编译失败问题记录

一、问题背景 1、QSSI说明 QSSI 是 Qualcomm Single System Image 的缩写&#xff0c;高通平台从Android Q开始&#xff0c;为了解决Android碎片化问题&#xff0c;把system.img和vendor.img进一步拆分&#xff0c;增加了QSSI编译选项&#xff0c;QSSI就是用来编译system.img的…

数据结构(ArrayList)

文章目录一、线性表二、顺序表2.1 ArrayList&#xff08;1&#xff09;概念&#xff08;2&#xff09;ArrayList 的构造&#xff08;3&#xff09;ArrayList 的方法&#xff08;4&#xff09; ArrayList的遍历&#xff08;5&#xff09;ArrayList的优缺点2.2 链表一、线性表 概…

symmetric funtion and antisymmetric function(对称性函数和反对称性函数)

symmetric funtion and antisymmetric functionantisymmetric functionsymmetric funtion附录今天看资料的时候遇到了一个说法&#xff0c;文中提及&#xff0c;f(x)f\left(x\right)f(x) 是一个 antisymmetric function&#xff0c;看到这个说法有点儿懵&#xff0c;这里特来记…

上海亚商投顾:沪指逼近3400点 CPO概念股再度爆发

上海亚商投顾前言&#xff1a;无惧大盘涨跌&#xff0c;解密龙虎榜资金&#xff0c;跟踪一线游资和机构资金动向&#xff0c;识别短期热点和强势个股。 市场情绪沪指今日震荡反弹&#xff0c;午后逼近3400点关口&#xff0c;创业板指则小幅调整。CPO概念股再度爆发&#xff0c;…

[oeasy]python00134_[趣味拓展]python起源_历史_Guido人生_ABC编程语言_Tanenbaum

python 历史 回忆上次内容 颜文字是kaomoji 把字符变成一种图画的方法一层叠一层很多好玩儿的kaomoji是一层层堆叠起来的meme 虚拟的表情也在真实世界有巨大影响 一步步地影响 字符编码就是这样一步步发展过来的python也是 一步步 发展到今天的 python究竟是 怎么发展的呢&…

异常(throwable)

异常 异常分类 &#xff08;1&#xff09;Throwable类 所有的异常类型都是它的子类&#xff0c;它派生两个子类Error、Exception。 &#xff08;2&#xff09;Error类 表示仅靠程序本身无法恢复的严重错误&#xff08;内存溢出动态链接失败、虚拟机错误&#xff09;&#…

分布式定时任务

本文引用了谷粒商城的课程 定时任务 定时任务是我们系统里面经常要用到的一些功能。如每天的支付订单要与支付宝进行对账操作、每个月定期进行财务汇总、在服务空闲时定时统计当天所有信息数据等。 定时任务有个非常流行的框架Quartz和Java原生API的Timer类。Spring框架也可以…

【面试题】20个常见的前端算法题,你全都会吗?

现在面试中&#xff0c;算法出现的频率越来越高了&#xff0c;大厂基本必考 今天给大家带来20个常见的前端算法题&#xff0c;重要的地方已添加注释&#xff0c;如有不正确的地方&#xff0c;欢迎多多指正&#x1f495; 大厂面试题分享 面试题库 前后端面试题库 &#xff08;…

Spring 6 正式“抛弃”feign

近期&#xff0c;Spring 6 的第一个 GA 版本发布了&#xff0c;其中带来了一个新的特性——HTTP Interface。这个新特性&#xff0c;可以让开发者将 HTTP 服务&#xff0c;定义成一个包含特定注解标记的方法的 Java 接口&#xff0c;然后通过对接口方法的调用&#xff0c;完成 …

Simulink仿真封装中的参数个对话框设置

目录 参数和对话框窗格 初始化窗格 文档窗格 为了更加直观和清晰的分析仿真&#xff0c;会将多个元件实现的一个功能封装在一起&#xff0c;通过参数对话框窗格&#xff0c;可以使用参数、显示和动作选项板中的对话框控制设计封装对话框。如图所示&#xff1a; 参数和对话框…

刘二大人《Pytorch深度学习实践》第六讲逻辑斯蒂回归

文章目录线性回归和逻辑斯蒂回归的区别课上代码交叉熵函数的理解线性回归和逻辑斯蒂回归的区别 线性回归一般用于预测连续值变量&#xff0c;如房价预测问题。 线性回归的一般表达式为&#xff1a; 代价函数为MSE&#xff08;均方误差&#xff09;&#xff1a; 其中权重thet…

Linux Shell 实现一键部署二进制Rabbitmq

rabbitmq 前言 RabbitMQ是实现了高级消息队列协议&#xff08;AMQP&#xff09;的开源消息代理软件&#xff08;亦称面向消息的中间件&#xff09;。RabbitMQ服务器是用Erlang语言编写的&#xff0c;而集群和故障转移是构建在开放电信平台框架上的。所有主要的编程语言均有与代…

openai的whisper语音识别介绍

openAI发布了chatgpt&#xff0c;光环一时无两。但是openAI不止有这一个项目&#xff0c;它的其他项目也非常值得我们去研究学习。 今天说说这个whisper项目 https://github.com/openai/whisper ta是关于语音识别的。它提出了一种通过大规模的弱监督来实现的语音识别的方法。…

C++之深入解析STL unordered_map的底层实现原理

C STL 标准库中&#xff0c;不仅是 unordered_map 容器&#xff0c;所有无序容器的底层实现都采用的是哈希表存储结构。更准确地说&#xff0c;是用“链地址法”&#xff08;又称“开链法”&#xff09;解决数据存储位置发生冲突的哈希表&#xff0c;整个存储结构如下所示&…

JVM 垃圾收集器详解

一、垃圾收集器 如果说收集算法是内存回收的方法论&#xff0c;那垃圾收集器就是内存回收的实践者。《Java虚拟机规范》中对垃圾收集器应该如何实现并没有做出任何规定&#xff0c;因此不同的厂商、不同版本的虚拟机所包含的垃圾收集器都可能会有很大差别&#xff0c;不同的虚…

基于遗传算法的中药药对挖掘系统的设计与实现

用数据挖掘技术研究了中药方剂配伍的规律。主要工作&#xff1a;分析了关联规则存在的问题&#xff0c;引入双向关联规则的概念&#xff1b;介绍了遗传算法的基本原理&#xff0c;研究了遗传算法在数据挖掘中的应用&#xff1b;将方剂库转换为位图矩阵&#xff0c;大大提高搜索…

Mac重启清理缓存会怎么样 mac清理缓存怎么清理

众所周知&#xff0c;Mac电脑有着流畅的操作系统&#xff0c;因此&#xff0c;很多用户都会选择使用Mac电脑办公。随着日常使用&#xff0c;系统缓存数据越来越大&#xff0c;某些Mac电脑&#xff08;尤其是小内存版本的Mac电脑&#xff09;可能会出现“系统”占存储空间比例较…

初始单片机.md

1.如何将HEX文件烧录到单片机 STC-ISP STC-ISP是一款单片机下载编程烧录软件&#xff0c;是针对STC系列单片机而设计的&#xff0c;可下载STC89系列、12C2052系列和12C5410等系列的STC单片机&#xff0c;使用简便。 思路&#xff1a;将电脑磁盘上已存在的文件通过串口的方式下…

python中第三方库xlrd和xlwt的使用教程

excel文档名称为联系人.xls&#xff0c;内容如下&#xff1a; 一、xlrd模块用法 1.打开excel文件并获取所有sheet import xlrd# 打开Excel文件读取数据 data xlrd.open_workbook(联系人.xls)sheet_name data.sheet_names() # 获取所有sheet名称 print(sheet_name) # [银…

python依次运行多个代码遇到的同步与异步问题

1、要实现在一个Python代码运行完后紧接着运行另一个Python代码&#xff0c;可以使用Python的subprocess模块。该模块可以创建新进程并与之交互&#xff0c;可以用于在Python代码中启动新的程序或脚本。 下面是一个示例代码&#xff0c;用于在运行完code1.py后紧接着运行code2…