温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用c#结构体

发布时间:2021-10-14 10:05:19 来源:亿速云 阅读:230 作者:iii 栏目:编程语言

本篇内容主要讲解“如何使用c#结构体”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何使用c#结构体”吧!

直接看c++和c#代码:

struct structpointer
{
	int id;
	int* ptrid;
};
void processstructpointer(structpointer *sp)
{
	if (sp == NULL)
		return;
	int* p;
	p = sp->ptrid;
	while (true)
	{
		if (*p != 0) //只要不是0就处理
		{
			cout << *p << endl;
			*p += 1;
			p += 1;
		}
		else
		{
			break;
		}
	}
}
        unsafe public struct structpointer
        {
            public int id;
            public int* ptrid;
        };
        [DllImport("ccalldll2.dll", EntryPoint = "processstructpointer", CallingConvention = CallingConvention.Cdecl)]
        public static extern unsafe void processstructpointer(structpointer *sp);
        private void button2_Click(object sender, EventArgs e)
        {
            structpointer[] sp = new structpointer[1];
            int[] ids = new int[3];
            ids[0] = 1; ids[1] = 5; ids[2] = 7;
            unsafe
            {
                ////int* p = &ids[0];//只能获取 fixed 语句初始值设定项内的未固定表达式的地址
                //fixed(structpointer* p = &sp[0])
                //{
                  
                //    //p->ptrid = &ids[0];//只能获取 fixed 语句初始值设定项内的未固定表达式的地址
                //}
                fixed(int *p = &ids[0])
                {
                    fixed(structpointer* pt = &sp[0])
                    {
                        pt->ptrid = p; //注意这种写法
                        processstructpointer(pt);
                        processstructpointer(pt);
                    }
                }                
            }
        }

注意:连续两次调用processtructpointer(pt)的现象:

1)当用ids[0] = 1; ids[1] = 5; ids[2] = 0;则一切现象都正常OK;

2)当用ids[0] = 1; ids[1] = 5; ids[2] = 7;则一切现象都不正确。

上面两种现象都好理解,关键是结构体,结构体指针,结构体成员是指针,结构体指针作参数在c++和c#之间是如何处理的。其实还有IntPtr可以处理struct相关的参数。

补充说明:

以前一直实验都是c++和c#中的struct的名称都是一样的,今天将上面的structpointer改为structpointerxback,其它c#中代码也对应修改名称,结果实验也是OK的。这说明:名称只是形式而已,真正从内存角度来说,c++处理的时候并不是以名称来看的,还是从内存物理结构来看。

到此,相信大家对“如何使用c#结构体”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI