开发者

how to copy from text box to struct C#

I need to copy the strings from text box to struct. is there any way to do it? here's what am trying:

public unsafe struct mystruc
{
    public byte[] install_name; // size limit 32 bytes
    public byte[] install_id;   // size limit 4 bytes
    public byte[] model_name;   // size limit 4 bytes
};

private void read_b_Click(object sender, EventArgs e)
{
    mystruc mstruc1 = new mystruc();

    //copy from textbox to struct    
    mstruc.install_name = Encoding.UTF8.GetBytes(installation_name_tb.Text);
    mstruc.install_开发者_StackOverflow社区id = Encoding.UTF8.GetBytes(installation_id_tb.Text);
    mstruc.model_name = Encoding.UTF8.GetBytes(model_tb.Text);    
}

and also other way round. its not working.. :( any help greatly appreciated


Where are you going to use this struct - I believe to invoke some Win32 style API. So the correct implementation would depend upon what that API is looking for. For example, if it is expecting ASCII characters (char), you need to use ASCIIEncoding. If is expecting unicode characters (WCHAR) then u should use UnicodeEncoding. I would advise you share that api to get more useful answers.

EDIT: I am not certain if you are invoking any unmanaged DLL or how have you decided your structure layout but following info may be useful:

If the idea is to write contents of structure where you are assuming it to have length of 40 bytes (three inline arrays of 32, 4 and 4 bytes) then it won't work "as is" in .NET. This is because, array are reference types (pointers to memory somewhere else) and .NET may choose field offset in order have aligned word boundaries - so solution is to use attributes to mark that structure layout. For example,

[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ascii)]
public struct mystruc
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
    [FieldOffset(0x00)]
    public byte[] install_name; // size limit 32 bytes

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    [FieldOffset(0x33)]
    public byte[] install_id;   // size limit 4 bytes

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    [FieldOffset(0x37)]
    public byte[] model_name;   // size limit 4 bytes
}

Here, we are saying that we will layout structure explicitly (using field offset) and then provided information for each field. This struct would be probably equivalent of what you wants. Or you have to play with these attributes as per your requirments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜