如何在 Flutter 中使用 dart:ffi 打印到控制台?

How do I Print to Console using dart:ffi in Flutter?

当 运行 我的 Flutter 应用程序(在 Android 上)时尝试从以下 C++ 代码打印到控制台 我是 运行 到 dart:ffi:

#include <iostream>

std::cout << "Hello, World!";

终端没有给我任何输出。我如何从 C++ 打印到 Flutter 终端?


我知道我的函数可以正常工作,因为我对指针/return 值进行了正确的操作。

编辑:当android上只有运行时,有一个更简单的方法。我已经更新了下面的答案。

您必须将打印函数的包装器传递到本机代码中

void wrappedPrint(Pointer<Utf8> arg){
  print(Utf8.fromUtf8(arg));
}

typedef _wrappedPrint_C = Void Function(Pointer<Utf8> a);
final wrappedPrintPointer = Pointer.fromFunction<_wrappedPrint_C>(_wrappedPrint_C);

final void Function(Pointer) initialize =
  _nativeLibrary
    .lookup<NativeFunction<Void Function(Pointer)>>("initialize")
    .asFunction<void Function(Pointer)>();

initialize(wrappedPrintPointer);

然后在您的 C 库中使用它:

void (*print)(char *);

void initialize(void (*printCallback)(char *)) {
    print = printCallback;
    print("C library initialized");
}

void someOtherFunction() {
    print("Hello World");
}

当 android 上只有 运行 时,事情会变得更简单。而不是以上所有,做:

只需使用 android 日志记录机制,它将显示在控制台上,至少在使用 flutter run 时是这样。我假设 flutter 使用应用程序的 PID 附加到 logcat。

为此,请将 CMakeLists.txt 更新为:

find_library( # Defines the name of the path variable that stores the
              # location of the NDK library.
              log-lib

              # Specifies the name of the NDK library that
              # CMake needs to locate.
              log )

# Links your native library against one or more other native libraries.
target_link_libraries( # Specifies the target library.
                       <your-libs-name-here>

                       # Links the log library to the target library.
                       ${log-lib} )

并在你的 c 库中执行:

#include <android/log.h>

void someOtherFunction() {
      __android_log_print(ANDROID_LOG_DEBUG, "flutter", "Hello world! You can use %s", "formatting");
}