C#指針使用簡析
C#指針的存在狀況簡析:指針在C\C++里面可是一個(gè)好東西,但是到j(luò)ava,.net的時(shí)代指針已經(jīng)被封裝起來,對用戶不可見,這點(diǎn)java做的非常的徹底。.net可能因?yàn)檫€存在一個(gè)托管C++,因此指針并沒有完全廢除,C#還是保留了指針的操作。
要使用指針首先要對使用指針的代碼用unsafe進(jìn)行進(jìn)行聲明,聲明和public聲明一樣,可以對整個(gè)類進(jìn)行聲明,也可以是類里面某個(gè)方法或者屬性。在代碼里什么后,還需要修改工程項(xiàng)目的Build屬性,讓編譯器支持指針的操作。
做好事前的工作就可以使用指針了。指針的使用方法和C++下使用沒有太多差別。只要編譯器不報(bào)錯(cuò)就沒有太大問題。
下面就C#指針來看其他指針的一些使用上的理解:
1. 指針類型可以是實(shí)體變量(int,double)也可以是enum,同時(shí)也支持結(jié)構(gòu)體變量struct。但不能是類。不過空指針可以指向類,只不過空指針不能進(jìn)行任何操作,也只能把空指針作為傳遞對象來使用。
2. C#提供一個(gè)的關(guān)鍵字stackalloc用于申請堆棧內(nèi)存。注意,這個(gè)申請內(nèi)存分配的是棧內(nèi)存,當(dāng)函數(shù)執(zhí)行完畢后,內(nèi)存會(huì)被自動(dòng)回收。不過我想用這個(gè)棧內(nèi)存基本可以解決40%的問題,而且使用的時(shí)候不必?fù)?dān)心內(nèi)存泄漏問題。
3. .net 好像不直接支持堆內(nèi)存的申請(這個(gè)對.net來說很危險(xiǎn)),不過我們可以通過調(diào)用win32 api 的方法進(jìn)行申請。這樣就可以解決剩下40%的問題。堆內(nèi)存申請的方法在MSDN里面有相關(guān)的文檔,具體實(shí)現(xiàn)代碼見附。
4. 結(jié)構(gòu)體是一個(gè)特殊的對象。他與類的定義就差一個(gè)關(guān)鍵字,使用方法也和類一樣,可以定義屬性,可以定義方法。但是在進(jìn)行指針操作的時(shí)候雙方就有很大的差別了。結(jié)構(gòu)體可以通過sizeof()取得大小,大小與結(jié)構(gòu)體里有多少實(shí)體變量有關(guān),但是如果struck里定義了類的對象,或者指針,sizeof可能會(huì)編譯不過(void* 的空指針例外,不過需要在結(jié)構(gòu)體聲明處加上unsafe)。
5. fixed關(guān)鍵字:目前了解的不多,不過有一個(gè)很實(shí)用的例子可以讓指針能夠和.net里的數(shù)組進(jìn)行交互操作:
- byte[] buffer = new byte[100];
- fixed (byte* p = buffer)
- {
- P[0] = 123;
- ……
- }
附C#指針的實(shí)現(xiàn):
- public unsafe class Memory
- {
- // Handle for the process heap.
- // This handle is used in all calls to the
- // HeapXXX APIs in the methods below.
- static int ph = GetProcessHeap();
- // Private instance constructor to prevent instantiation.
- private Memory() { }
- // Allocates a memory block of the given size.
- //The allocated memory is
- // automatically initialized to zero.
- public static void* Alloc(int size)
- {
- void* result = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);
- if (result == null) throw new OutOfMemoryException();
- return result;
- }
- // Copies count bytes from src to dst.
- //The source and destination
- // blocks are permitted to overlap.
- public static void Copy(void* src, void* dst, int count)
- {
- byte* ps = (byte*)src;
- byte* pd = (byte*)dst;
- if (ps > pd)
- {
- for (; count != 0; count--) *pd++ = *ps++;
- }
- else if (ps < pd)
- {
- for (ps += count, pd += count;
- count != 0; count--) *--pd = *--ps;
- }
- }
- // Frees a memory block.
- public static void Free(void* block)
- {
- if (!HeapFree(ph, 0, block))
- throw new InvalidOperationException();
- }
- // Re-allocates a memory block.
- //If the reallocation request is for a
- // larger size, the additional region of memory is automatically
- // initialized to zero.
- public static void* ReAlloc(void* block, int size)
- {
- void* result = HeapReAlloc(ph, HEAP_ZERO_MEMORY, block, size);
- if (result == null) throw new OutOfMemoryException();
- return result;
- }
- // Returns the size of a memory block.
- public static int SizeOf(void* block)
- {
- int result = HeapSize(ph, 0, block);
- if (result == -1) throw new InvalidOperationException();
- return result;
- }
- // Heap API flags
- const int HEAP_ZERO_MEMORY = 0x00000008;
- // Heap API functions
- [DllImport("kernel32")]
- static extern int GetProcessHeap();
- [DllImport("kernel32")]
- static extern void* HeapAlloc(int hHeap, int flags, int size);
- [DllImport("kernel32")]
- static extern bool HeapFree(int hHeap, int flags, void* block);
- [DllImport("kernel32")]
- static extern void* HeapReAlloc(int hHeap, int flags,
- void* block, int size);
- [DllImport("kernel32")]
- static extern int HeapSize(int hHeap, int flags, void* block);
- }
C#指針方面的內(nèi)容就向你介紹到這里,希望對你了解學(xué)習(xí)C#指針有所幫助。
【編輯推薦】