How to pass const char* to dart?

Viewed 78

I don't understand how to pass (..., const char *request) to dart function I used Pointer but there is an error in .asFunction()

import 'dart:ffi';
import 'dart:io' show Directory;
import 'package:path/path.dart' as path;
import 'package:ffi/ffi.dart';

// FFI signature void td_send (int client_id, const char *request) C Function
typedef C_td_send = Void Function(int client_id, Pointer<Utf8> request);
// Dart type definition for calling the C foreign function
typedef td_send = void Function(int client_id, Pointer<Utf8> request);

void main(List<String> arguments) async {
// Open the dynamic library
var libraryPath =
path.join(Directory.current.path, '/usr/local/lib/', 'libtdjson.so');
final dylib = DynamicLibrary.open(libraryPath);

final td_send td_request = dylib
  .lookup<NativeFunction<C_td_send>>('td_send')
  .asFunction(); <---  Error: Expected type 'NativeFunction<Void Function(int, Pointer<Utf8>)>' to be a valid and instantiated subtype of 'NativeType'
1 Answers

The signature was wrong

C code:

#include <stdio.h>

void td_send(int client_id, const char *request) {
printf("> %d ",client_id);
printf(request);
}

Dart Code :

import 'dart:ffi';
import 'dart:io' show Directory;
import 'package:path/path.dart' as path; 
import 'package:ffi/ffi.dart';

// FFI C foreign function : "td_send (int client_id, const char *request)"
typedef CTdSend = Void Function(Int32 clientId, Pointer<Utf8> request);
// Dart type definition for calling the C foreign function
typedef _TdSend = void Function(int clientId, Pointer<Utf8> request);

void main(List<String> arguments) async {
  // Open the dynamic library
  var libraryPath =
  path.join(Directory.current.path, '/home/user/IdeaProjects/TestC/',      'dartc.so');
  final dylib = DynamicLibrary.open(libraryPath);
  late final _TdSend _tdSend = dylib
  .lookup<NativeFunction<CTdSend>>('td_send').asFunction();

  _tdSend(100, "hello world !!".toNativeUtf8());
Related