We call CPP dll in Flutter using Flutter ffi. This is our CPP function in dll.
extern "C" __declspec(dllexport) void StartServerSession (const char* Name,const char* js,int& sessionID,int& ERESULT,void(eventhandler)(const char,int))
export "C"__declspec(dllexport) void InitializeServer(void(eventhandler)(const char,int)){ PtrObj->Initialize(eventhandler); }
This Flutter FFI code
final DynamicLibrary DllPath = DynamicLibrary.open('path to dll');
typedef InitializeFunc = Void Function(Pointer<Void> eventhandler);
typedef InitializeFun = void Function(Pointer<Void> eventhandler);
typedef StartServerSessionC = Void Function(Pointer<Utf8> Name, Pointer<Utf8> js, Pointer<Pointer<Int32>> sessionID, Pointer<Pointer<Int32>> ERESULT,Pointer<Void> eventhandler);
typedef StartServerSession = void Function(Pointer<Utf8> Name, Pointer<Utf8> js, Pointer<Pointer<Int32>> sessionID, Pointer<Pointer<Int32>> ERESULT,Pointer<Void> eventhandler);
void eventHandler(Pointer<Utf8> response, int length) {
print('Response: ${response.cast<Utf8>.toDartString()}');
}
final initialize = DllPath
.lookupFunction<InitializeFunc , InitializeFun>('Initialize');
final startServerSession = DllPath
.lookupFunction<StartServerSessionC, StartServerSession>('StartServerSession');
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('FFI Demo')),
body: Center(
child: ElevatedButton(
onPressed: () async {
// Example usage of the FFI functions
await callStartServerIsolate();
},
child: Text('Call DLL Function'),
),
),
),
);
}
}
void StartServerFunction(SendPort sendPort)
{
print("1");
Pointer<Utf8> name = ('path to second dll'.toNativeUtf8());
Pointer<Utf8> js = {json value}.toNativeUtf8();
// Allocate memory for sessionID and ERESULT
final sessionID = calloc<Int32>();
final ERESULT = calloc<Int32>();
initialize (Pointer.fromFunction<Void Function(Pointer<Utf8>, Int32)>(eventHandler)as Pointer<Void>);
// Run startOTXSession on a separate isolate
startServerSession (
name,
js,
sessionID as Pointer<Pointer<Int32>>,
ERESULT as Pointer<Pointer<Int32>>,
Pointer.fromFunction<Void Function(Pointer<Utf8>, Int32)>(eventHandler)as Pointer<Void>);
sendPort.send("task Complete");
}
Future<Void> callStartServerIsolate()async{
final receivePort = ReceivePort();
final sendPort = receivePort.sendPort;
await Isolate.spawn(StartServerFunction,sendPort)
}
** Showing an error that cannot invoke a native callback outside of an isolate.** Now what happened started SeverSession execution, **but internally they started a separate thread in the DLL file with a callback. **