1

我一直在尝试编写一个可以与 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')

但如果我直接执行 dart 而不是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 集成的合适文章。

4

1 回答 1

2

但是如果我直接执行飞镖而不是flutter run

Dart 不是沙盒应用,而 Flutter 应用默认是沙盒。这就是为什么您只会在 Flutter 应用程序中收到沙盒错误。

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

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

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

于 2020-07-21T16:36:35.787 回答