溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何使用c#結構體

發布時間:2021-10-14 10:05:19 來源:億速云 閱讀:254 作者: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

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女