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);
}
标签:调用,handle,C++,debugPrint,ffi,import,Pointer,flutter
From: https://www.cnblogs.com/yangwenli/p/18592584