dahall / Vanara

A set of .NET libraries for Windows implementing PInvoke calls to many native Windows APIs with supporting wrappers.
MIT License
1.75k stars 190 forks source link

[Bug] MB_GetString make exe crashed and ExitCode is 3221226356 (0xc0000374) #428

Closed emako closed 9 months ago

emako commented 10 months ago

Describe the bug and how to reproduce

BUG code:

using Vanara.PInvoke;

var src = User32.MB_GetString(1); // Crash here

// I estimate `LPWStr` cannot be used in the Chinese system.
// [return: MarshalAs(UnmanagedType.LPWStr)]

My solution code:

public static class User32X
{
    [DllImport(Lib.User32, SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern nint MB_GetString(uint wBtn);
}

var src = Marshal.PtrToStringAuto(User32X.MB_GetString(1)); // return src is "取消"(meaning `Cancel`)

What code is involved

User32.MB_GetString

Expected behavior

MB_GetString make exe crashed and ExitCode is 3221226356 (0xc0000374)

Screenshots

程序“[4784] XXX.exe”已退出,返回值为 3221226356 (0xc0000374)。

Translated to English: The program '[4784] XXX. exe' has exited with a return value of 3221226356 (0xc0000374).

dahall commented 9 months ago

Would you mind testing the following?

[DllImport(Lib.User32, SetLastError = true, CharSet = CharSet.Unicode)]
public static extern string? MB_GetString(uint wBtn);

You can leave off the '?' after 'string' if you are not using nullability settings.

dahall commented 9 months ago

I have this resolved and need to update the master branch. For the return value, it should use StrPtrUni instead of string?. The value returned is a pointer into system memory. I'll close one I commit the fix.