title: How to prevent JNI from overwriting GetLastError()
body: <p>We are implementing a one-to-one mapping of some <code>winapi</code> methods, for the <a href="https://code.google.com/p/xidobi/" rel="nofollow noreferrer">xidobi</a> serial port project. The mapping of the <code>C</code> methods to java works as expected, but for an unknown reason <code>GetLastError()</code> get cleared.</p>
  
  <p>Here is the <strong>C-Code</strong>:</p>
  
  <pre><code>// CreateFile ////////////////////////////////////////////////////////////
  JNIEXPORT jint JNICALL
  Java_org_xidobi_OS_CreateFile(JNIEnv *env, jobject this,
      jstring lpFileName,
      jint dwDesiredAccess,
      jint dwShareMode,
      jint lpSecurityAttributes,
      jint dwCreationDisposition,
      jint dwFlagsAndAttributes,
      jint hTemplateFile) {
  
  const char* fileName = (*env)-&gt;GetStringUTFChars(env, lpFileName, NULL);
  
  HANDLE handle = CreateFile(fileName,
                              dwDesiredAccess,
                              dwShareMode,
                              (LPSECURITY_ATTRIBUTES) lpSecurityAttributes,
                              dwCreationDisposition,
                              dwFlagsAndAttributes,
                              (HANDLE) hTemplateFile);
  
  (*env)-&gt;ReleaseStringUTFChars(env, lpFileName, fileName);
  
  return (jint) handle;
  }
  
  // GetLastError ////////////////////////////////////////////////////////////
  JNIEXPORT jint JNICALL
  Java_org_xidobi_OS_GetLastError(JNIEnv *env, jobject this) {
      return (jint)  GetLastError();
  }
  </code></pre>
  
  <p>In <strong>Java</strong> we call the mapped native methods in like this:</p>
  
  <pre><code>int handle = os.CreateFile("\\\\.\\" + portName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  
  if (handle != INVALID_HANDLE_VALUE)
      return handle;
  int lastError= os.GetLastError(); //-&gt; sometimes 0 (ERROR_SUCCESS)
  </code></pre>
  
  <p>We figured out that if we call <code>GetLastError()</code> in C right after <code>CreateFile(..)</code> the correct error code is returned. Since the one-to-one mapping is dead simple we assume that JNI or the VM calls <code>SetLastError()</code> itself and clears our last error.</p>
  
  <p>We don't want to give up the one-to-one mapping design, so what can we do to solve this puzzle?</p>
  
  <p>Here is a similar question that doesn't help in this case: <a href="https://stackoverflow.com/questions/7665384/createfile-returns-invalid-handle-value-but-getlasterror-is-error-success?rq=1">CreateFile() returns INVALID_HANDLE_VALUE but GetLastError() is ERROR_SUCCESS</a></p>