How to use OpenCV with dart:ffi on iOS

Issue

I am developing a flutter plugin that uses OpenCV as a dependency to do some image processing. I created a bridge and initilized lookup function as mentioned in here. The basic sum function works, however as soon as I add

s.dependency "OpenCV2"

on my plugins pod spec file. My pod install fails

[!] The 'Pods-Runner' target has transitive dependencies that include statically linked binaries: (/.../native_add/example/ios/Pods/OpenCV2/opencv2.framework)

Meaning there is some static library within the private pod. Thus I enabled

s.static_framework = true

on my podspec file and ran pod install. Pods get installed, and app runs too but now I get another issue telling that dart:ffi is not able to find the symbol.

2020-06-05 15:52:55.419438+0545 Runner[759:830306] [VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: Invalid argument(s): Failed to lookup symbol (dlsym(RTLD_DEFAULT, native_add): symbol not found)
#0      DynamicLibrary.lookup (dart:ffi-patch/ffi_dynamic_library_patch.dart:33:29)
#1      nativeAdd (package:native_add/native_add.dart:13:6)
#2      nativeAdd (package:native_add/native_add.dart:12:34)

So how to make dart:ffi find symbols while enabling static_framework. There are very few resources related to dart:ffi.

Update

Lookup Function:

final DynamicLibrary nativeAddLib = Platform.isAndroid
    ? DynamicLibrary.open("libnative_add.so")
    : DynamicLibrary.process();

final int Function(int x, int y) nativeAdd = nativeAddLib
    .lookup<NativeFunction<Int32 Function(Int32, Int32)>>("native_add")
    .asFunction();

C++ function

extern "C" __attribute__((visibility("default"))) __attribute__((used))
int32_t native_add(int32_t x, int32_t y) {
    return x + y;
}

Solution

So after couple of days of research. At the time of this writing(2020-06-07), I found that having a static framework on a flutter plugin code is not possible(I might be wrong). For more details check here

But here is how I solved the issue, I copied every custom .cpp file to my Runner target and used dart:ffi to call from the core target. Also the pod that I needed is now on main PodFile. Same with the android, change your CMakeLists file to point c++ files from Runner folder inside iOS and link them with the grad

Answered By – Aawaz Gyawali

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *