flutter中呼叫C++的庫

杨文利發表於2024-12-07

Dart呼叫C++的庫

  1. 安裝ffi庫 flutter pub add ffi
  2. 如果是C++必須使用C的方式匯出介面
import 'dart:ffi';
import 'dart:io';
import "package:ffi/ffi.dart";

final DynamicLibrary ff = Platform.isWindows
    ? DynamicLibrary.open("live666.dll")
    : throw UnsupportedError("only Windows is supported");

// 定義 C 函式的簽名
typedef CLive666Init = Pointer<Void> Function(Pointer<Utf8>, Pointer<Utf8>);

// 定義 Dart 函式的簽名
typedef DartLive666Init = Pointer<Void> Function(Pointer<Utf8>, Pointer<Utf8>);

// 查詢並繫結函式
final live666Init = ff.lookupFunction<CLive666Init, DartLive666Init>('live666_init');
  1. 呼叫
  void _invokeCpp(){
    try{
      debugPrint("Current working directory: ${Directory.current.path}");

      final handle = live666Init(url, reg);
      if (handle.address == 0) {
        debugPrint("Initialization failed, null pointer returned.");
      } else {
        debugPrint("Initialization succeeded, handle: 0x${handle.address.toRadixString(16)}");
      }
    } on UnsupportedError{
      debugPrint("沒有找到動態庫");
    }
    malloc.free(url);
    malloc.free(reg);
  }

相關文章