Skip to content

How to get a string from an inline array in a struct? #635

Answered by AArnott
Lightczx asked this question in Q&A
Discussion options

You must be logged in to vote

If this were using a UTF-16 character array, there would be a ToString() method on the struct that would produce what you want.
But as this is a CHAR inline array, you have to do it yourself. I filed #636 to improve this.

This is how you can do it. It produces the string "abc":

using System.Text;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.System.Diagnostics.ToolHelp;

MODULEENTRY32 m = default;
m.szModule._0 = (CHAR)(byte)'a';
m.szModule._1 = (CHAR)(byte)'b';
m.szModule._2 = (CHAR)(byte)'c';

unsafe
{
    byte* pszModule = (byte*)&m.szModule;
    string szModule = Encoding.UTF8.GetString(pszModule, GetLength(pszModule));
}

static unsafe int GetLength(byte* p…

Replies: 2 comments 8 replies

Comment options

You must be logged in to vote
1 reply
@Lightczx
Comment options

Answer selected by Lightczx
Comment options

You must be logged in to vote
7 replies
@AArnott
Comment options

@AArnott
Comment options

@jnm2
Comment options

@AArnott
Comment options

@Lightczx
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants