65.9K
CodeProject is changing. Read more.
Home

How to copy a String into a struct using C#

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.95/5 (24 votes)

Jun 10, 2004

viewsIcon

109342

downloadIcon

2

How to copy a String into a struct using C#

Introduction

This article show a simple code snippet using which you can copy a string into a struct.

Using the code

using System;
using System.Runtime.InteropServices;
using System.Text;

class Class1
{

    [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
    public struct MyStruct
    {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst=4)] public string fname;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst=4)] public string lname;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst=7)] public string phone;
    }
    
    public static void Main()
    {
        string buffer = "abcdefgh2223333";
        IntPtr pBuf = Marshal.StringToBSTR(buffer);
        MyStruct ms = (MyStruct)Marshal.PtrToStructure(pBuf,typeof(MyStruct));
        Console.WriteLine("fname is: {0}",ms.fname);
        Console.WriteLine("lname is: {0}",ms.lname);
        Console.WriteLine("phone is: {0}",ms.phone);
        Marshal.FreeBSTR(pBuf);
    }
}