android - 如何使用 dart :ffi in Flutter? 打印到控制台

标签 android c++ flutter dart dart-ffi

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

#include <iostream>

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

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

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

最佳答案

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

您必须将包装器传递给 print 函数到 native 代码中

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 lib 中执行以下操作:
#include <android/log.h>

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

关于android - 如何使用 dart :ffi in Flutter? 打印到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60577769/

相关文章:

flutter - 在 Flutter 中减少文本基线以下的区域

android - 按下后退出 android 应用程序

c++ - MacOS 上的 Qt .nib 问题

c++ - 取消引用结构 union 的结构

c++ - 如何定义派生类的非成员构造函数(在类头中)

flutter - 如何从列表中删除特定项目?

android - ClassCastException : BasicHttpResponse cannot be cast to org. apache.http.HttpEntity 安卓

android - 如何使用 OpenStreetMap/OpenLayers?

android - 如何在android中将图像转换为字节数组并将字节数组转换为base64字符串?

dart - 在 flutter release 模式下,一个快照中的 native 代码如何在 mulity arch cpu 中运行