I would recommend to create some new macro that gest/sets last error, instead of repeating the same tricky code thousand times.
e.g.

#ifdef TSRM_WIN32
# define CWD_STATE_FREE_ERR(state) do { \
        DWORD last_error = GetLastError(); \
        CWD_STATE_FREE(state); \
        SetLastError(last_error); \
    } while (0)
#else
# define CWD_STATE_FREE_ERR(state) CWD_STATE_FREE(state)
#endif