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

C Marshal类基本概念和入门示例程序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

    这是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()); } } } } 

讯享网

 

小讯
上一篇 2025-02-15 17:21
下一篇 2025-03-01 08:32

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/51218.html