如何访问 Flutter 桌面版 (macOS) 应用程序中的方法

How to access methods in a Flutter for desktop (macOS) app

我一直在尝试编写一个可以与 Go 方法通信的 Flutter 桌面应用程序。

转到文件:

package main

import "C"
import "fmt"

func PrintHello() {
    fmt.Print("Hello,World")
}

func main() {}
import 'dart:ffi' as ffi;

typedef PrintHello_func = ffi.Void Function();
typedef PrintHello = void Function();

void ffi_test(List<String> arguments) {
  var path = '/path/to/libhello_ffi.dylib';

  final ffi.DynamicLibrary dylib = ffi.DynamicLibrary.open(path);

  final PrintHello hello = dylib
      .lookup<ffi.NativeFunction<PrintHello_func>>('PrintHello')
      .asFunction();

  hello();
}

以上Flutter代码执行失败,报错:

The following ArgumentError was thrown while handling a gesture:
Invalid argument(s): Failed to load dynamic library
(dlopen(/path/to/libhello_ffi.dylib, 1):
no suitable image found.  Did find:
    file system sandbox blocked open() of
'/path/to/libhello_ffi.dylib')

但是如果我直接执行飞镖而不是 flutter run,它会工作得很好。

我什至尝试创建一个单独的 FFI 包,但不幸的是它也失败了。

FFI 包名称:/my_app/packages/libhello_ffi

我把libhello_ffi.dylib文件放在了/my_app/packages/libhello_ffi/macos目录下

颤动代码:


import 'dart:ffi';
import 'dart:io';

final DynamicLibrary _dl = _open();

DynamicLibrary _open() {
  if (Platform.isMacOS) return DynamicLibrary.executable();
  throw UnsupportedError('This platform is not supported.');
}

typedef sayhello_C = Void Function();
typedef sayhello_Dart = void Function();

void sayhello() {
  _dl.lookup<NativeFunction<sayhello_C>>('PrintHello')
      .asFunction();
}

错误:

The following ArgumentError was thrown while handling a gesture:
Invalid argument(s): Failed to lookup symbol (dlsym(RTLD_DEFAULT, PrintHello): symbol not found)

When the exception was thrown, this was the stack:
#0      DynamicLibrary.lookup (dart:ffi-patch/ffi_dynamic_library_patch.dart:31:29)
#1      sayhello (package:libhello_ffi/ffi.dart:17:7)
#2      LibhelloFfi.sayhello (package:libhello_ffi/libhello_ffi.dart:5:12)
#3      ffi_test (package:squash_archiver/features/home/ui/widgets/ffi_test.dart:10:13)
#4      _HomeScreenState._buildTestFfi.<anonymous closure> (package:squash_archiver/features/home/ui/pages/home_screen.dart:73:13)
#5      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
#6      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)

网上没有关于 Go 和 Flutter for Desktop 集成的合适文章。

But it works just fine if I execute the dart directly instead of flutter run

Dart 不是沙盒应用,而 Flutter 应用 is sandboxed by default。这就是为什么您只会在 Flutter 应用程序中收到沙箱错误。

I placed the libhello_ffi.dylib file under /my_app/packages/libhello_ffi/macos directory

这听起来像是源代码树中的一个位置,而不是您的应用程序。除非禁用沙箱,否则无法在应用程序外部引用任意文件。

如果您只是在本地进行测试,关闭沙盒是一个简单的解决方案。如果你想要一些你可以分发的东西,你需要将库打包到你的包中(通过将它作为捆绑资源添加到你的 Xcode 项目中)无论如何,在这一点上我希望加载它即使在沙箱中也能工作.