Dart调用C++的库
- 安装ffi库 flutter pub add ffi
- 如果是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');
- 调用
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);
}
使用ffigen工具包调用C++库
- 安装工具包 dart pub add -d ffigen && dart pub add ffi
- 在 pubspec.yaml 文件中添加以下配置
ffigen:
output: 'lib/cpp/api/generated_bindings.dart'
name: 'live666'
headers:
entry-points:
- 'cpp/api/test.h'
llvm-path:
- 'C:\Users\Jack-PC\llvm'
- 生成绑定
dart run ffigen
- 调用
import 'generated_bindings.dart';
void main() {
final lib = NativeLibrary(DynamicLibrary.open('path_to_your_library.so'));
final result = lib.sum(1, 2);
print('Sum: $result');
}
flutter与C++源码交互
- 在源码目录新建 CMakeLists.txt 文件
cmake_minimum_required(VERSION 3.4)
# 项目名称
if (CMAKE_SYSTEM_NAME MATCHES "Windows")
set(PROJECT_NAME "libNative")
else()
set(PROJECT_NAME "Native")
endif()
project(${PROJECT_NAME} LANGUAGES CXX)
# 源文件
add_library(${PROJECT_NAME} SHARED
"./test1.cpp"
)
# Windows 需要把dll拷贝到bin目录
IF (WIN32)
# 动态库的输出目录
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/$<$<CONFIG:DEBUG>:Debug>$<$<CONFIG:RELEASE>:Release>")
# 安装动态库的目标目录
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")
# 安装动态库,到执行目录
install(FILES "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${PROJECT_NAME}.dll" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime)
ENDIF()
- 如果是Android在 .\android\app\build.gradle 文件添加如下代码
externalNativeBuild {
// Encapsulates your CMake build configurations.
cmake {
// 指定一个CMake 编译脚本的相对目录。
path "../../cpp/api/CMakeLists.txt"
}
}
- 如果是Windows在./Windows/CMakeLists.txt中添加如下代码
add_subdirectory("../cpp/api/" test1)
- 编写源代码
#include <stdint.h>
#ifdef WIN32
#define DART_API extern "C" __declspec(dllexport)
#else
#define DART_API extern "C" __attribute__((visibility("default"))) __attribute__((used))
#endif
DART_API int32_t native_add(int32_t x, int32_t y) {
return x + y;
}
- 使用 dart run ffigen生成dart代码