2

I'm trying to include a C library in my flutter app. I have some .h files, and a .a file. If I understand correctly, the .h files are headers, and the .a file is a statically linked library.

My goal is to run some functions from that library into my flutter code, but I find the flutter documentation very unclear about how to do it. I don't know anything about C, so I really struggle to understand the code, and I don't really know where to start.

My question is: Is it possible to run code from .a file in a flutter app, and how can I do it? Or do I need a .so file, or the source code?

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
Manu
  • 372
  • 2
  • 12
  • You can only do dynamic linking. No static linking. – Christopher Moore Apr 04 '21 at 16:25
  • I see that you also tagged your question with `[flutter]`. Which Flutter platform are you targeting? – Richard Heap Apr 15 '21 at 14:02
  • I target iOS and Android devices, if that's your question? – Manu Apr 17 '21 at 15:54
  • Note that the comment above is only partly true. Yes, Dart ffi requires a dynamic library but there's no reason why you can't wrap a static library into a dynamic one.. If you just have a `.a` library, you need to write some C wrapper functions that call the functions exposed by the library which in turn exposes some method up to the ffi layer. The Flutter plugin project makes this relatively easy as the compilation and build task is done for you as part of the Flutter build. – Richard Heap May 11 '21 at 21:28

1 Answers1

3

As always, start with a Flutter plugin project. Obviously, refer to the instructions here: https://flutter.dev/docs/development/platform-integration/c-interop

Specifically, for the .a files

For iOS, create a folder projectname/ios/lib and copy the .a file there, then add an extra line to your podspec:

s.ios.vendored_libraries = 'lib/libFooBar.a'

For Android, create a folder projectname/android/lib and copy the .a file there - there may be several for different architectures.

In build.gradle add, near the top:

def my_lib_folder = new File(projectDir, 'lib')

and in the defaultConfig under externalNativeBuild add in the cmakesection: arguments "-DMY_LIB_FOLDER=${my_lib_folder}"

These two actions cause that definition to be passed to CMake.

Now when you add you C files to the project (see the instructions in the link at the top) they will link with the .a libraries you provided.

Now, make use of that in the CMakeLists.txt

If you don't have a target_link_libraries section, add it and you can now add this incantation to refer to your .a library:

${MY_LIB_FOLDER}/libSomelibrary${ANDROID_ABI}.a
Richard Heap
  • 48,344
  • 9
  • 130
  • 112