This is the fourth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Function calls should be the most common scenario in Dart and C interactions. Let’s take a look at how you can call C functions from Dart and Dart functions from C.

The Dart adjustable C

No returned value

As an example, Dart calls a C function and prints a sentence in the C function.

sample.h

void hello_world(a);
Copy the code

sample.c

void hello_world(a)
{
    printf("[CPP]: Hello World");
}
Copy the code

main.dart

late final _hello_worldPtr =
      _lookup<ffi.NativeFunction<ffi.Void Function() > > ('hello_world');
late final _hello_world = _hello_worldPtr.asFunction<void Function(a) > ();print('[Dart]: ${_hello_world()}');
Copy the code

Results output

[CPP]: Hello World
[Dart]: null
Copy the code

Returns a value

When C has a return value, sample.h can be received via type conversion

char* getName(a);
Copy the code

sample.c

char* getName(a)
{
    return "My name is Mobile phone";
}
Copy the code

main.dart

late final _getNamePtr =
      _lookup<ffi.NativeFunction<ffi.Pointer<ffi.Int8> Function() > > ('getName');
late final _getName =
    _getNamePtr.asFunction<ffi.Pointer<ffi.Int8> Function(a) > ();print("[Dart]: return value ->"+_getName().cast<Utf8>().toDartString());
Copy the code

Output result:

[Dart]: there is a return value -> My name is mobile phoneCopy the code

Have the arguments

Use C printf function to implement a Dart print function

sample.h

void cPrint(char *str);
Copy the code

sample.c

void cPrint(char *str) 
{
    printf("[CPP]: %s", str);
    free(str);
}
Copy the code

main.dart

late final _cPrintPtr =
      _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<ffi.Int8>)>>(
          'cPrint');
late final _cPrint =
    _cPrintPtr.asFunction<void Function(ffi.Pointer<ffi.Int8>)>();
_cPrint("I think this output makes sense.".toNativeUtf8().cast<ffi.Int8>());
Copy the code

The output

[CPP]: I think this output makes senseCopy the code

So you have an output function.