如何在C#中将固定字节/字符[100]转换为托管字符[]? [英] How to convert fixed byte/char[100] to managed char[] in C#?

查看:95
本文介绍了如何在C#中将固定字节/字符[100]转换为托管字符[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中将固定字节或char [100]转换为托管char []的最佳方法是什么?我最终不得不使用指针算法,我想知道是否有更简单的方法-类似于memcpy或其他方法?

What's the best way to convert a fixed byte or char[100] to a managed char[] in C#? I ended up having to use pointer arithmetic and I'm wondering if there is an easier way -- something like a memcpy or another way?

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

namespace StructTest
{

    [StructLayout(LayoutKind.Explicit)]
    unsafe struct OuterType
    {
        private const int BUFFER_SIZE = 100;

        [FieldOffset(0)]
        private int transactionType;

        [FieldOffset(0)]
        private fixed byte writeBuffer[BUFFER_SIZE];

        public int TransactionType
        {
            get { return transactionType; }
            set { transactionType = value; }
        }

        public char[] WriteBuffer
        {
            set
            {
                char[] newBuffer = value;

                fixed (byte* b = writeBuffer)
                {
                    byte* bptr = b;
                    for (int i = 0; i < newBuffer.Length; i++)
                    {
                         *bptr++ = (byte) newBuffer[i];
                    }
                }
            }

            get
            {
                char[] newBuffer = new char[BUFFER_SIZE];

                fixed (byte* b = writeBuffer)
                {
                    byte* bptr = b;
                    for (int i = 0; i < newBuffer.Length; i++)
                    {
                        newBuffer[i] = (char) *bptr++;
                    }
                }

                return newBuffer;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            OuterType t = new OuterType();
            t.WriteBuffer = "hello there".ToCharArray();
            System.Console.WriteLine(t.WriteBuffer);
        }
    }
}

推荐答案

您可以使用

You can use Marshal.Copy for that. Notice it is also overloaded for byte[], which might be a more appropriate data type.

这篇关于如何在C#中将固定字节/字符[100]转换为托管字符[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆