码迷,mamicode.com
首页 > 其他好文 > 详细

MarshalDemo

时间:2017-02-22 11:12:35      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:top   runtime   userdata   using   rgs   pre   system   sha   const   

using System;
using System.Runtime.InteropServices;

namespace MarshalDemo
{
    class Program
    {
        private static UserData userData;
        static void Main(string[] args)
        {
            userData.myString = "abc";
            userData.myInt = 100;

            int size = Marshal.SizeOf(userData);
            IntPtr pUserData = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(userData, pUserData, true);

            UserData userData2 = (UserData)Marshal.PtrToStructure(pUserData, typeof(UserData));
            Marshal.FreeHGlobal(pUserData);

            Console.WriteLine(userData2.myString);
            Console.WriteLine(userData2.myInt);

            Console.Read();
        }
    }
    [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
    public struct UserData
    {
        [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 15)]
        public string myString;
        public int myInt;
    }
}

 

MarshalDemo

标签:top   runtime   userdata   using   rgs   pre   system   sha   const   

原文地址:http://www.cnblogs.com/xinzheng/p/6427845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!