openLib method

DynamicLibrary openLib()

Implementation

ffi.DynamicLibrary openLib() {
  var isFlutterTest = Platform.environment.containsKey('FLUTTER_TEST');

  if (Platform.isMacOS || Platform.isIOS) {
    if (isFlutterTest) {
      final appDirectory =
          _findAppDirectory(Directory('build/macos/Build/Products/Debug'));
      var ffiFile = Path.join(
          appDirectory.path, "Contents", "Frameworks", "$_libraryName.dylib");
      validateTestFFIFile(ffiFile);
      return ffi.DynamicLibrary.open(ffiFile);
    }
    if (Platform.isMacOS) {
      return ffi.DynamicLibrary.open("$_libraryName.dylib");
    }
    if (Platform.isIOS) {
      return ffi.DynamicLibrary.process();
    }
  }

  if (Platform.isAndroid || Platform.isLinux) {
    if (isFlutterTest) {
      var arch =
          Platform.resolvedExecutable.contains("linux-x64") ? "x64" : "arm64";

      var ffiFile = 'build/linux/$arch/debug/bundle/lib/$_libraryName.so';
      validateTestFFIFile(ffiFile);
      return ffi.DynamicLibrary.open(ffiFile);
    }

    if (Platform.isLinux) {
      try {
        return ffi.DynamicLibrary.open("$_libraryName.so");
      } catch (e) {
        print(e);
        var binary = File("/proc/self/cmdline").readAsStringSync();
        var suggestedFile =
            Path.join(Path.dirname(binary), "lib", "$_libraryName.so");
        return ffi.DynamicLibrary.open(suggestedFile);
      }
    }

    if (Platform.isAndroid) {
      try {
        return ffi.DynamicLibrary.open("$_libraryName.so");
      } catch (e) {
        print("fallback to open DynamicLibrary on older devices");
        //fallback for devices that cannot load dynamic libraries by name: load the library with an absolute path
        //read the app id
        var appid = File("/proc/self/cmdline").readAsStringSync();
        // the file /proc/self/cmdline returns a string with many trailing \0 characters, which makes the string pretty useless for dart, many
        // operations will not work correctly. remove these trailing zero bytes.
        appid = String.fromCharCodes(
            appid.codeUnits.where((element) => element != 0));
        final loadPath = "/data/data/$appid/lib/$_libraryName.so";
        return ffi.DynamicLibrary.open(loadPath);
      }
    }
  }

  if (Platform.isWindows) {
    if (isFlutterTest) {
      var arch =
          Platform.resolvedExecutable.contains("x64") ? "x64" : "arm64";

      var ffiFile = Path.canonicalize(Path.join(
          r'build\windows', arch, r'runner\Debug', '$_libraryName.dll'));
      validateTestFFIFile(ffiFile);
      return ffi.DynamicLibrary.open(ffiFile);
    }
    return ffi.DynamicLibrary.open("$_libraryName.dll");
  }

  throw UnsupportedError('Unknown platform: ${Platform.operatingSystem}');
}