Supercharge Your Flutter Apps: Seamlessly Integrate C++ with Dart using DLLs
AYON KARMAKAR

AYON KARMAKAR @ayon_ssp

About: Backend Engineer | I build secure and scalable applications.

Location:
/dev/loop?
Joined:
Feb 15, 2022

Supercharge Your Flutter Apps: Seamlessly Integrate C++ with Dart using DLLs

Publish Date: Mar 22
15 0

Unlock the full potential of your Flutter applications by integrating powerful C++ functionalities. This guide will walk you through the process of using Dynamic Link Libraries (DLLs) to enhance your Dart code. Let's dive in! 🌊


Prerequisites 🛠️

  1. Flutter Setup: Ensure Flutter is installed and configured on your system.
  2. C++ Compiler: Install MinGW or Visual Studio for compiling the DLL.
  3. Dart FFI: Familiarity with the dart:ffi package is helpful but not required.

Step 1: Create the C++ DLL

Here is a simple C++ example with two functions: one to add two integers and another to concatenate two strings.
example_code.h:

#ifndef DATAPROCESSOR_H
#define DATAPROCESSOR_H

#include <string>

extern "C" __declspec(dllexport) int add(int a, int b);
extern "C" __declspec(dllexport) const char* concatenateStrings(const char* str1, const char* str2);
extern "C" __declspec(dllexport) void freeString(void* str);

#endif
Enter fullscreen mode Exit fullscreen mode

Step 2: Write Your C++ Code 💻

Create a C++ file (example_code.cpp) with the following content:

#include "example_code.h"
#include <string>
#include <cstring>

extern "C" __declspec(dllexport) int add(int a, int b) {
    return a + b;
}

extern "C" __declspec(dllexport) const char* concatenateStrings(const char* str1, const char* str2) {
    std::string result = std::string(str1) + std::string(str2);
    char* concatenated = new char[result.size() + 1];
    strcpy(concatenated, result.c_str());
    return concatenated;
}

extern "C" __declspec(dllexport) void freeString(void* str) {
    delete[] static_cast<char*>(str);
}
Enter fullscreen mode Exit fullscreen mode

Compile the DLL

Run the following command in your terminal to compile the DLL:

cl /I . /LD example_code.cpp /Fe:example_code.dll /EHsc /std:c++17
Enter fullscreen mode Exit fullscreen mode

This will generate example_code.dll in your current directory.


Step 3: Integrate C++ with Dart 🧩

  1. Create a Dart File: In your Dart project, create a file named example.dart.
  2. Add FFI Dependency: Open pubspec.yaml and add the ffi package:

    dependencies:
      ffi: ^1.1.2
    
  3. Write Dart Code: Use the following Dart code to call the C++ functions:
    example.dart:

import 'dart:ffi';
import 'package:ffi/ffi.dart';

// Define function signatures
typedef AddC = Int32 Function(Int32 a, Int32 b);
typedef AddDart = int Function(int a, int b);

typedef ConcatC = Pointer<Utf8> Function(Pointer<Utf8> str1, Pointer<Utf8> str2);
typedef ConcatDart = Pointer<Utf8> Function(Pointer<Utf8> str1, Pointer<Utf8> str2);

typedef FreeC = Void Function(Pointer<Utf8> str);
typedef FreeDart = void Function(Pointer<Utf8> str);

class MyLibrary {
  final DynamicLibrary _dll;

  MyLibrary(this._dll);

  int add(int a, int b) {
    final AddDart add = _dll.lookupFunction<AddC, AddDart>('add');
    return add(a, b);
  }

  String concatenateStrings(String str1, String str2) {
    final ConcatDart concat = _dll.lookupFunction<ConcatC, ConcatDart>('concatenateStrings');
    final FreeDart free = _dll.lookupFunction<FreeC, FreeDart>('freeString');

    final Pointer<Utf8> str1Pointer = str1.toNativeUtf8();
    final Pointer<Utf8> str2Pointer = str2.toNativeUtf8();

    final Pointer<Utf8> resultPointer = concat(str1Pointer, str2Pointer);

    calloc.free(str1Pointer);
    calloc.free(str2Pointer);

    if (resultPointer != nullptr) {
      final String result = resultPointer.toDartString();
      free(resultPointer);
      return result;
    } else {
      return '';
    }
  }
}

void main() {
  final dylib = DynamicLibrary.open('example_code.dll');
  final myLibrary = MyLibrary(dylib);

  print('Addition Result: ${myLibrary.add(10, 20)}');

  final result = myLibrary.concatenateStrings('Hello, ', 'World!');
  print('Concatenation Result: $result');
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Test Your Application 🧪

  1. Place the generated example_code.dll in the same directory as your Dart file.
  2. Run the Dart application:
   dart example.dart
Enter fullscreen mode Exit fullscreen mode
  1. You should see the following output:
   Addition Result: 30
   Concatenation Result: Hello, World!
Enter fullscreen mode Exit fullscreen mode

Key Takeaways 📚

1.Use dart:ffi to call C++ functions from Dart.
2.Always free dynamically allocated memory in C++ to prevent memory leaks.
3.Make sure the DLL file is accessible by your Flutter or Dart application.

By following these steps, you can easily extend your Flutter application with native functionality using DLL files. Happy coding! 🧑‍💻

Comments 0 total

Не удалось загрузить комментарии.
Add comment