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

cre*_*not 4 c++ android dart flutter dart-ffi

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

#include <iostream>

std::cout << "Hello, World!";
Run Code Online (Sandbox Code Playgroud)

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


我知道我的函数可以正常工作,因为我在指针/返回值上得到了正确的操作。

t.a*_*mal 6

编辑:仅在 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);
Run Code Online (Sandbox Code Playgroud)

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

void (*print)(char *);

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

void someOtherFunction() {
    print("Hello World");
}
Run Code Online (Sandbox Code Playgroud)

当仅在 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} )
Run Code Online (Sandbox Code Playgroud)

并在您的 c lib 中执行以下操作:

#include <android/log.h>

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