It’s possible that you can place any data type even though it is not advisable because “struct” belongs to a value type. But the actual problem arises when we place a type like array or some thing as a buffer and call some unmanaged external API to fill it. In this case when a garbage collection occurs there is a chance that the memory of the buffer can get reallocated as a result of GC’s memory compaction process and thus a page fault will result when the API function try to access this buffer. A kind of work around can be done using the “Fixed” keyword which will pin that data type to memory. But this is not the exact one. For a long time I was searching for a solution and I came across a code snippet in one web site which is as follows
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct tstruct
{
[FieldOffset(0)]
public byte service1;
[FieldOffset(1)]
public byte service2;
[FieldOffset(2)]
public byte data1;
[FieldOffset(12)]
public byte data2;
[FieldOffset(22)]
public byte max_data1;
[FieldOffset(23)]
public byte max_data2;
}
To access the data1/2 arrays,use:
tstruct t;
...
byte* b1=&t.data1;
byte* b2=&t.data2;
Then just access b1/2 like a normal array. The thing is that there is will be no index-checking or other thing done by CLR because it directly considers it as a perfect value type and will get completely allocated into stack there by avoiding all operations of GC
The one shot answer for your programming queries & concepts about Microsoft . Net Framework technology
The topics described here concentrates fully on pure .Net Framework, describing actual meaning of some programming concepts, FCL and best practices. However you will be using these concepts in all . Net framework compatible languages like Microsoft visual basic .net (VB.Net) or C# .Net (csharp.Net) to build a web application (Asp.Net) or Desktop applications (winforms .net) or Web/Windows services
This blog has moved!
You will be automatically redirected to the new address. If that does not occur, visit
http://Codemine.net
and update your bookmarks.
0 comments:
Post a Comment