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

Wrong Marsha.SizeOf for MODULEENTRY32 #449

Closed elgl closed 3 months ago

elgl commented 3 months ago

Describe the bug and how to reproduce

Using CreateToolhelp32Snapshot to obtain the name of first module. Marshal.SizeOf returned a wrong number, which resulted into failure of Module32First.

What code is involved

SafeHSNAPSHOT hToolHelp = CreateToolhelp32Snapshot(TH32CS.TH32CS_SNAPMODULE | TH32CS.TH32CS_SNAPMODULE32, Pid); if (hToolHelp.IsInvalid) return null; MODULEENTRY32 moduleEntry = new MODULEENTRY32(); moduleEntry.dwSize = (uint)Marshal.SizeOf(moduleEntry); Module32First(hToolHelp, ref moduleEntry); Console.WriteLine(moduleEntry.dwSize + " " + moduleEntry.szExePath);

//moduleEntry.dwSize produce 1080, moduleEntry.szExePath is null. However, if I declare those structures or fucntions by myself, it will produce correct answers. Not too sure if it is Vanara's issue or Microsoft issues.

Expected behavior

The first module should be produced with szExePath, but it is not.

elgl commented 3 months ago

Ok I found the issue. Vanara declare the strucutre in wide char, but import Module32First from Ansi mode. Here is the solution.

    [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true, EntryPoint = "Module32FirstW")]
    private static extern bool Module32FirstW(HSNAPSHOT hSnapshot, ref MODULEENTRY32 lpme);

It works.

dahall commented 3 months ago

Fixed in 4.0.1