Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run desktop app Lost connection to device. #908

Open
GavinDon opened this issue Jun 18, 2022 · 2 comments
Open

Run desktop app Lost connection to device. #908

GavinDon opened this issue Jun 18, 2022 · 2 comments

Comments

@GavinDon
Copy link

run windows . flutter calls the DLL, and already gets the value returned by c. But then it will lose connection to device.
I don't know what's causing this.Below is my code
` Future sendAPDUHex(String cmd) async {
int sendLen = cmd.length ~/ 2;
try {

  Pointer<Uint8> apduRLen = calloc.allocate(sizeOf<Uint8>());

  Pointer<Uint8> apduResData = calloc.allocate(sizeOf<Uint8>());

  Pointer<ffi.Utf8> sendData = cmd.toNativeUtf8();

  int apduRst =
      await cpuAPDUHexFun(icDev, sendLen, sendData, apduRLen, apduResData);
  debugPrint("apduRst=$apduRst");
  if (apduRst != 0) {
    return "";
  }
  Pointer<ffi.Utf8> dataFromAddress =
      Pointer.fromAddress(apduResData.address);
  String message = dataFromAddress.toDartString();
  debugPrint("message=$message");
  await Future.microtask(() => calloc.free(apduRLen));
  await Future.microtask(() => calloc.free(apduResData));
  await Future.microtask(() => calloc.free(dataFromAddress));
  return message;
} on ArgumentError catch (e) {
  return e.toString();
} on Exception catch (e) {
  return e.toString();
}

}`

@dcharkes
Copy link
Collaborator

But then it will lose connection to device.

Any segfault would cause this. For example reading memory that has been freed, or double free.

Add prints to figure out till where it works.

debugPrint("apduRst=$apduRst");

This print still succeeds?

You can use .address to see what memory you're trying to access.

Side note:

calloc.allocate(sizeOf<Uint8>());

Use calloc<Uint8>() instead, sizeOf will be automatic.

Side note 2:

await Future.microtask(() => calloc.free(apduRLen));

Use calloc.free(apduRLen). FFI calls are fast, no need to use async here.

Side note 3:

Instead of manual frees, you can use the Arena:

https://github.com/dart-lang/ffi/blob/master/lib/src/arena.dart

@GavinDon
Copy link
Author

The modification according to the above three points will still lose.

The printing is normal. I don't know if it is a memory allocation problem. Sometimes the first time it is normal, the second time it runs, it will lose

@dcharkes dcharkes transferred this issue from dart-archive/ffi Jan 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants