0

i tried call cpp code in dart but failed

import 'dart:ffi' as ffi;
import 'package:ffi/ffi.dart' as pkgffi;

void main(List<String> arguments) {
  try {
    ffi.DynamicLibrary dynamicLibrary = ffi.DynamicLibrary.open("./lib.so");
    var res = dynamicLibrary.lookupFunction<ffi.Void Function(), void Function()>("play").call();
  } catch (e) {
    print(e);
  }
}
#include <iostream>
#include <stdio.h>

void play()
{
    using namespace std;
    cout << "Come up and C++ me some" << endl;
} 

command compile librarys

g++ lib.cpp -o lib.so -fPIC --shared

error message

Invalid argument(s): Failed to lookup symbol 'play': ./azka.so: undefined symbol: play

can you help me to call function play in dart?

noobdev
  • 95
  • 1
  • 6
  • FYI, this is not C++. The C++ language does not have a `var` keyword, and the `main` function returns `int` not `void`. – Thomas Matthews Oct 04 '22 at 23:55
  • Your `play` function doesn't use anything from `stdio.h`, so you should remove that `#include`. – Thomas Matthews Oct 04 '22 at 23:56
  • I've deleted stdio.h, and I tried to compile and run again but can't get the play function, while with c language it works but not with cpp, can you solve this problem? – noobdev Oct 05 '22 at 00:15
  • How does this work with the C language compiler? There is no keyword `var` in C. In `C`, the declaration of `main` is: `int main(int argument_count, char * * argument_list)`. Also, `cout` is not defined in the C language. The `operator<<` in C language is a left shift and undefined for string literals. The C language also doesn't support `try` and `catch`. I don't understand how it works with the C compiler? Set one of your compiler parameters to `-Wall` and pay attention to the error messages. – Thomas Matthews Oct 05 '22 at 00:25
  • Is the `dart` language expecting the C function protocol or the C++? You'll need to explore how to interface the C++ language to the `dart` language. Search the internet for "dart interface C++ extern". – Thomas Matthews Oct 05 '22 at 00:29
  • thanks, i edit my code with add extern "C" + i add argument in command compile with `-lstdc++` now it's going well, thank you very much – noobdev Oct 05 '22 at 00:43

0 Answers0