Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Marshal::GetLastWin32Error have unpredictable result

Discussion in 'Windows' started by Ruonan, Feb 8, 2023.

  1. Ruonan

    Ruonan

    Joined:
    Dec 6, 2012
    Posts:
    53
    Hey guys, I am working on a windows app build with unity3d. I try to pinvoke some user32.dll function and try to call Marshal::GetLastWin32Error() to get error code if there is any.


    I followed the guide line in those two pages: call Marshal::GetLastWin32Errorcall() instead of kernal32.dll's GetLastError and call it immediately after a user32 function call.

    Marshal.GetLastWin32Error Method (System.Runtime.InteropServices) | Microsoft Learn
    GetLastError function (errhandlingapi.h) - Win32 apps | Microsoft Learn

    My app worked just fine until I add Marshal::GetLastWin32Error call. Marshal::GetLastWin32Error just get some random errors.

    Can any help me with this problem? I am really confused .
    Thanks.
     
    Last edited: Feb 9, 2023
  2. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,446
  3. Ruonan

    Ruonan

    Joined:
    Dec 6, 2012
    Posts:
    53
    Oops it is typo, I am actully call Marshal.GetLastWin32Error();

    This is how I define those function.
    Code (CSharp):
    1.  
    2. [DllImport("user32.dll", SetLastError = true)]
    3. public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    and my function is like:
    Code (CSharp):
    1. var progman = User32.FindWindow(PROGMAN, null);
    2. var errorCode = Marshal.GetLastWin32Error();
    3. if (errorCode != 0)
    4.        UnityEngine.Debug.LogException(new Win32Exception(errorCode));
    Counld that be the error code from other program? I don't know if this function is multi-thread safe.
     
  4. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,446
    No, it's stored in a thread local variable. However, I see an error in your usage of FindWindow: you are only supposed to call GetLastWin32Error() if FindWindow function fails. It will not set the error if it succeeds, so you might be seeing an error from a previous call to something else. Try this:

    Code (csharp):
    1. var progman = User32.FindWindow(PROGMAN, null);
    2. if (progman == IntPtr.Zero)
    3.     UnityEngine.Debug.LogException(new Win32Exception(Marshal.GetLastWin32Error()));
     
  5. Ruonan

    Ruonan

    Joined:
    Dec 6, 2012
    Posts:
    53

    Oh, Thanks! I will try this one. Get back to this if it works.