编程语言
首页 > 编程语言> > [C#]快速将字符串转换为结构

[C#]快速将字符串转换为结构

作者:互联网

[C#]快速将字符串转换为结构


看到MSDN上请问将一个字符串copy到一个结构中最快的方式为何?这篇的发问,做些纪录:

要将字符串快速转换为结构,首先我们必须要在结构上加些Attribute,像是设定每个字段所占用的型态、大小...等:

[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;
}

在转换时先透过Marshal.StringToBSTR将字符串转为指针,再透过Marshal.PtrToStructure将指针转换为指定的结构型态,最后再用Marshal.FreeBSTR把刚刚的指针位置给释放掉就可以了:

private static T ConvertToStruct(string val)
{
    IntPtr valPoint = Marshal.StringToBSTR(val);
    T ret = (T)Marshal.PtrToStructure(valPoint, typeof(T));
    Marshal.FreeBSTR(valPoint);
    return ret;
}

完整范例如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

namespace ConsoleApplication20
{
    class Program
    {
        [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;
        }

        private static T ConvertToStruct(string val)
        {
            IntPtr valPoint = Marshal.StringToBSTR(val);
            T ret = (T)Marshal.PtrToStructure(valPoint, typeof(T));
            Marshal.FreeBSTR(valPoint);
            return ret;
        }

        public static void Main()
        {
            MyStruct ms = ConvertToStruct("abcdefgh2223333");
            Console.WriteLine("fname is: {0}", ms.fname);
            Console.WriteLine("lname is: {0}", ms.lname);
            Console.WriteLine("phone is: {0}", ms.phone);         
        }
    }
}

运行后可以发现abcdefgh2223333字符串会依照我们在结构字段所设定的长度自动填入:

image

Link

原文:大专栏  [C#]快速将字符串转换为结构



标签:转换,string,C#,ByValTStr,Marshal,字符串,using,public,UnmanagedType
来源: https://www.cnblogs.com/petewell/p/11457663.html