fix: macos ptr access

This commit is contained in:
Kingtous 2023-02-19 23:22:40 -08:00
parent 6fd900c479
commit 4f059a9138
6 changed files with 72 additions and 56 deletions

View file

@ -1,5 +1,7 @@
import 'dart:ffi';
import 'dart:math';
import 'dart:typed_data';
import 'package:ffi/ffi.dart';
import 'package:flutter/material.dart';
import 'dart:async';
@ -7,7 +9,28 @@ import 'dart:async';
import 'package:flutter/services.dart';
import 'package:texture_rgba_renderer/texture_rgba_renderer.dart';
typedef F1 = Void Function(
Pointer<Void> ptr, Pointer<Uint8> buffer, Int32 width, Int32 height);
typedef F1Dart = void Function(
Pointer<Void> ptr, Pointer<Uint8> buffer, int width, int height);
class Native {
Native._();
static get _instance => Native._()..init();
static get instance => _instance;
late F1Dart onRgba;
init() {
final lib = DynamicLibrary.process();
onRgba = lib.lookupFunction<F1, F1Dart>("FlutterRgbaRendererPluginOnRgba");
}
}
void main() {
// Load the native instance.
final instance = Native.instance;
runApp(const MyApp());
}
@ -36,7 +59,7 @@ class _MyAppState extends State<MyApp> {
if (textureId != -1) {
debugPrint("Texture register success, textureId=$textureId");
_textureRgbaRendererPlugin.getTexturePtr(key).then((value) {
debugPrint("texture ptr: $value");
debugPrint("texture ptr: ${value.toRadixString(16)}");
setState(() {
texturePtr = value;
});
@ -53,12 +76,18 @@ class _MyAppState extends State<MyApp> {
void start() {
debugPrint("start mockPic");
Timer.periodic(const Duration(milliseconds: 30), (timer) async {
data = mockPicture(width, height);
final res =
await _textureRgbaRendererPlugin.onRgba(key, data!, height, width);
if (!res) {
debugPrint("WARN: render failed");
}
// data = mockPicture(width, height);
// Method.1: with MethodChannel
// final res =
// await _textureRgbaRendererPlugin.onRgba(key, data!, height, width);
// if (!res) {
// debugPrint("WARN: render failed");
// }
final dataPtr = mockPicturePtr(width, height);
// Method.2: with native ffi
Native.instance.onRgba(
Pointer.fromAddress(texturePtr).cast<Void>(), dataPtr, width, height);
malloc.free(dataPtr);
});
}
@ -77,6 +106,16 @@ class _MyAppState extends State<MyApp> {
return Uint8List.fromList(pic);
}
Pointer<Uint8> mockPicturePtr(int width, int height) {
final pic = List.generate(width * height * 4, (index) {
return random.nextInt(255);
});
final pic_addr = malloc.allocate(pic.length).cast<Uint8>();
final list = pic_addr.asTypedList(pic.length);
list.setRange(0, pic.length, pic);
return pic_addr;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
@ -99,7 +138,7 @@ class _MyAppState extends State<MyApp> {
Align(
alignment: Alignment.topLeft,
child: Text(
"texture id: $textureId, texture memory address: $texturePtr"),
"texture id: $textureId, texture memory address: ${texturePtr.toRadixString(16)}"),
),
Align(
alignment: Alignment.bottomCenter,