简体   繁体   中英

JNA Invalid memory access when writing to file

For debug reasons I am writing a jna wrapper for a C++ DLL (compiled with gcc and mingw32)

write16Byte.dll

void write16Byte(const BYTE* mem) {
  FILE* out = fopen("BSTRvalues.txt", "a+");
  if (out == NULL) {
    printf("Error opening file!\n");
  return;
  }
  for (int i=0; i<16; i++) fprintf(out, "0x%x ", mem[i]);
  fwprintf(out, L"\n");
  fclose(out);
}

jna wrapper

public interface W16BDll extends com.sun.jna.Library {
  W16BDll INSTANCE = (W16BDll)com.sun.jna.Native.loadLibrary("write16Byte.dll", W16BDll.class);
  void write16Byte(com.sun.jna.Memory version);
}

The call of fprintf resultts in "java.lang.Error: Invalid memory access" because when I remove the fprintf everything works fine (I already read the thread in JNA Invalid memory access when writing to stdout )

If you turn on warnings in your compiler ( -Wall in gcc), it will tell you that you've mismatched your format string and actual argument.

"%x" requires an int parameter; you're providing const BYTE . Normally I'd expect this to just produce garbage, but depending on the CPU, arch, and stack layout you can get a range of failures.

You need to cast mem[i] to int (or use a format compatible with const BYTE ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM