本文介绍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&gt; 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&gt;('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/platformintegration/android/c-interop

这里是关于转换Cstring 为Gostring.
https://github.com/go-flutter-desktop/go-flutter/issues/334#issuecomment-575987613
https://gist.github.com/sjindel-google/b88c964eb260e09280e588c41c6af3e5

原文地址:https://blog.csdn.net/shelutai/article/details/130132625

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_21128.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注