SOVERFLOW
SOVERFLOW

Reputation: 1

C++ library passes incorrect / inconsistent data to flutter using dart:FFI

I have a Flutter application that uses a c++ library using the Dart:ffi package.

My c++ code listens for events whenever a barcode is scanned, this triggers a callback in Dart which then displays said barcode on the screen. I am doing 2 things in my c++ code:

  1. Logging it to a .txt file
  2. Displaying it on the screen through a callback.

When logging the data to a .txt file it's always correct. Whenever passing that same data to a callback that displays it on the screen there's 3 scenario's:

  1. It is empty
  2. It is correct
  3. The first character is missing, in my flutter console it's missing on my screen it looks like []

There are no weird characters either it's a simple CODE128 barcode like LOREM;IPSUM

My current solution is having the callback read the data from the .txt file, but I am curious why it doesn't work with the callback.

Code samples;

Flutter:

typedef InitializeScannerFunc = Void Function(Pointer<NativeFunction<BarcodeCallback>>);
typedef InitializeScanner = void Function(Pointer<NativeFunction<BarcodeCallback>>);
typedef BarcodeCallback = Void Function(Pointer<Utf8>);

final InitializeScanner initializeScannerFunc = dylib.lookup<NativeFunction<InitializeScannerFunc>>('InitializeScanner').asFunction();
final Pointer<NativeFunction<BarcodeCallback>> barcodeCallbackPtr = Pointer.fromFunction<BarcodeCallback>(barcodeCallback);
final nativeCallable = NativeCallable<BarcodeCallback>.listener(barcodeCallback);

FloatingActionButton(
    onPressed: () {    
        initializeScannerFunc(nativeCallable.nativeFunction);
    },
),              

C++

void invokeBarcodeCallback(const char* barcodeData) {
    // Call the callback function with the barcode data
    if (callbackFunc != nullptr) {
        std::string data = barcodeData;
        logMessage("invokeBarcodeCallback: " + data);
        callbackFunc(barcodeData); 
    }
}

Can provide more code samples if needed.

Edit: I haven't done c++ untill now to communicate with the scanner.

Upvotes: 0

Views: 87

Answers (0)

Related Questions