首页 > Windows开发 > 详细

C# Marshal类基本概念和入门示例程序

时间:2021-05-08 16:44:21      阅读:27      评论:0      收藏:0      [点我收藏+]

marshal:直译为“编排”, 在计算机中特 指将数据按某种描述格式编排出来,通常来说一般是从非文本格式到文本格式的数据转化。
unmarshal是指marshal的逆过程。比如在WebService中,我们需要把java对象以xml方式表示并在网络间传输,把java对象转化成xml片段的过程就是marshal.

 

微软对C#中Marshal类描述的链接在此;

https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal?view=net-5.0

Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks, and converting managed to unmanaged types, as well as other miscellaneous methods used when interacting with unmanaged code.
提供一个方法集合,分配非托管内存,拷贝非托管内存块,转换托管和非托管类型,以及一些和非托管代码交互的杂类方法;

    这是Marshal类的基本功能;.net一共包含四个Marshal类,每个都有一些方法;

 

下面来看一个Marshal类基本程序;程序运行结果如下;

 

技术分享图片

代码如下;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace marshalDemo1
{
    public struct Point
    {
        public Int32 x, y;
    }

    public partial class Form1 : Form
    {

        [DllImport("Kernel32", ExactSpelling = true, SetLastError = true)]
        static extern Boolean CloseHandle(IntPtr h);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = Marshal.SystemDefaultCharSize.ToString();
            textBox2.Text = Marshal.SystemMaxDBCSCharSize.ToString();
            textBox3.Text = Marshal.SizeOf(typeof(Point)).ToString();
            Point p = new Point(); 
            textBox4.Text = Marshal.SizeOf(p).ToString();
            IntPtr hglobal = Marshal.AllocHGlobal(100);
            textBox5.Text = hglobal.ToString();
            Marshal.FreeHGlobal(hglobal);

            Boolean f = CloseHandle(new IntPtr(-1));
            if (!f)
            {
                Console.WriteLine("CloseHandle call failed with an error code of: {0}",
                    Marshal.GetLastWin32Error());
            }
        }
    }
}

C# Marshal类基本概念和入门示例程序

原文:https://www.cnblogs.com/wuchangjian/p/14744023.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!