How to use a c++ code in Flutter Desktop Application?

Issue

How to develop a custom plugin using C++ for desktop application and how to use C++ language in my Flutter code and how to access it. Is there any proper documentation for accessing C++ program in the dart language?

Solution

The best bet you have is using dart VM’s FFI (foreign function interface) to bind to C APIs. You can mark functions in your C++ code to be "exported" to C as follows

extern "C" void myExportedFunction() {}

The extern "C" here prevents the compiler from mangling the function name while compilation.

You can then compile your c++ code to a dynamic library (.so for Linux, .dll for windows, .dylib for mac os), and load it. A code example to call myExportedFunction would be

import 'dart:ffi';

DynamicLibrary loadLibrary() {
  return DynamicLibrary.open('path/to/my/library.extension'); // extension would be .so for linux, .dll for windows and so on
}

void executeMyFunction() {
  final lib = loadLibrary();
  final myFunction = lib.lookup<NativeFunction<Void Function()>>('myExportedFunction').asFunction();

  myFunction();
}

You can check out the documentation at:

And some examples at:

Answered By – Akshit Garg

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.