Just My Life & My Work

由於 Flutter 是剛發展沒多久的程式語言,所以會遇到平台程式語言(Objective-C/Swift/Jave/Kotlin)有實作的功能,但 Flutter 還沒有的狀況,若我們不想要花時間開發,我們可以透過 Platform Channel,來直接使用平台的功能。🤪

還有另一種狀況,就是原生語言(C/C++)有實作的功能,但 Flutter 還沒有的狀況,此時我們可以使用什麼?Dart FFI

今天要來學習 Dart FFI。Dart 是 Google 開發的程式語言,那麼什麼是 FFI 呢?

A foreign function interface (FFI) is a mechanism by which a program written in one programming language can call routines or make use of services written in another.

我是透過最下方連結的文章,來學習此使用 Dart FFI 呼叫 C 程式,透過簡單的實作來了解前後邏輯,之後要透過 Flutter 來呼叫使用 OpenCV 也不是難事囉~😎

In the process, you’ll learn:

  1. About FFI and how it lets Dart code invoke code written in other languages.
  2. How FFI differs from Flutter platform channels.
  3. To automatically compile and link C code when building a Flutter app.
  4. How a Flutter app can use FFI to call code written in C.

先宣告一下我所實作的環境,太舊版本的 Flutter 和 Dart 無法實現喔!

  • Flutter 2.2.1 • channel stable • https://github.com/flutter/flutter.git
  • Framework • revision 02c026b03c (7 months ago) • 2021-05-27 12:24:44 -0700
  • Engine • revision 0fdb562ac8
  • Tools • Dart 2.13.1

然後我們的主角 Package 是 ffi: ^1.0.0,需要在 pubspec.yaml 指明。

接下來就是我學習的過程記錄,可參考:https://github.com/happymanx/Weather_FFI

這是我們要在 library 找 function,但是還不存在時,會跳出錯誤訊息。左圖會是 iOS,又圖則是 Android。

下圖是僅回傳數字。

下圖是回傳字串~

下圖是回傳結構~

下列程式碼是我建立的 weather.c

//
// Created by HappyMan on 2022/1/6.
//
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdlib.h>

double get_temperature()
{
  return 77.0f;
}

char* get_forecast() {
  char* forecast = "HappyBoy";
  char* forecast_m = malloc(strlen(forecast));
  strcpy(forecast_m, forecast);
  return forecast_m;
}

struct ThreeDayForecast  {
  double today;
  double tomorrow;
  double day_after;
};

double fahrenheit_to_celsius(double temperature) {
  return (5.0f / 9.0f) * (temperature - 32);
}

// 1
struct ThreeDayForecast get_three_day_forecast(bool useCelsius) {

  // 2
  struct ThreeDayForecast forecast;
  forecast.today = 77.0f;
  forecast.tomorrow = 78.0f;
  forecast.day_after = 79.0f;

  // 3
  if(useCelsius) {
    forecast.today = fahrenheit_to_celsius(forecast.today);
    forecast.tomorrow = fahrenheit_to_celsius(forecast.tomorrow);
    forecast.day_after = fahrenheit_to_celsius(forecast.day_after);
  }
  // 4
  return forecast;
}

/*
1. Accepts a bool indicating whether to return Celsius or Fahrenheit values.
2. Instantiates a struct with some very boring and static values, representing the forecasted temperature over the next three days.
3. Converts these values to Celsius if useCelsius is true.
4. Returns the struct.
*/

若要知道 Dart 如何呼叫 C 程式,請見最後的連結~😗

參考:Calling Native Libraries in Flutter with Dart FFI

隨意留個言吧:)~

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料

標籤雲