0

Friends

I am calling a native C++ programme I have written from Dart.

The problem I am having is that the parameters I am passing are not being received on the C++ side.

I have a structure with a buffer pointer and two ints. A function that takes the parameter and another int. The function just prints out the parameters.

The structure members are all zero and the passed integer is corrupted.

The C++ code:

#include <stdint.h>
#include <stdio.h>

struct ParametersTest {
    uint8_t * pixelBuffer;
    int64_t width;
    int64_t height;
};
extern "C" __attribute__((visibility("default"))) __attribute__((used))
void test_ffi_parameters(struct ParametersTest parameters, int64_t testint){
    printf("In the C++ function. testInt: %d Parameters.width %d Parameters.height %d buffer pointer: %p\n", 
        testint, parameters.width, parameters.height, parameters.pixelBuffer);
    // create_image(parameters.pixelBuffer, parameters.width, parameters.height);
}

I load the functions:

final DynamicLibrary externalLib = DynamicLibrary.process();

class ParametersTest extends Struct {
  
  external Pointer<Uint8> pixelBuffer;
  
  @Int()
  external int width;
  
  @Int()
  external int height;
}

final void Function(ParametersTest p, int t) testFfiWithParameters = 
       externalLib.
       lookup<NativeFunction<Void
                Function(ParametersTest, Int64)>>('test_ffi_parameters').
                asFunction();

And finally I call it:

  final pointer = malloc.allocate<ParametersTest>(sizeOf<ParametersTest>());
  final parameters = pointer.ref;
  parameters.width = width;
  parameters.height = height;
  parameters.pixelBuffer = malloc(width * height * 4);
  testFfiWithParameters(parameters, 1234);

It is printing out: In the C++ function. testInt: 1366 Parameters.width 0 Parameters.height 0 buffer pointer: 0x0

The members of parameters are zeroed in the C++ code (not in Dart). The integer parameter is corrupted.

Wrog
  • 21
  • 5
  • 1
    Probably not the issue but the type for `width` and `height` are not `Int()` but `Int64()` if it should match your C++ code. The `Int()` are documented as "Typically a signed 32-bit integer." so that would mean your end up with a wrongly sized struct. – julemand101 Jul 27 '22 at 08:14
  • Try passing `pointer` instead of `parameters` having changed the signature to `struct ParametersTest *parameters`, and adjusted the Dart end lookup to match – Richard Heap Jul 27 '22 at 15:57
  • A combination of both work: Passing the parameter as a Pointer and `@Int64()` annotations. – Wrog Jul 27 '22 at 20:50

0 Answers0