PDA

View Full Version : سوال: اندازه متغییر ها در حافظه کامپیوتر



alireza_tavakol
یک شنبه 04 مرداد 1388, 16:18 عصر
من اگه بخواهم بدونم فلان متغییر تعریف شده در برنامه ام چقدر حافظه رو اشغال کرده باید چی کار کنم؟

این متغییر ممکنه آرایه انوع jagged یا ArrayList و یا ... باشد

در واقع من نمی دونم در یه همچین مواقعی چطوری باید از ( ) sizeof استفاده کنم؟:متفکر:

hozouri
یک شنبه 04 مرداد 1388, 16:37 عصر
دوست عزیز برای این کار بهتره از فضای نام System.Runtime.InteropServices از کلاس
Marshal
استفاده کنی. توی اون sizeof برای همچین مواردی هست...

البته باید به درستی استفاده بشه ....

یه مثال از خود مایکروسافت می ذارم ...



using System;
using System.Runtime.InteropServices;

public struct Point
{
public int x;
public int y;
}

class Example
{

static void Main()
{

// Create a point struct.
Point p;
p.x = 1;
p.y = 1;

Console.WriteLine("The value of first point is " + p.x + " and " + p.y + ".");

// Initialize unmanged memory to hold the struct.
IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(p));

try
{

// Copy the struct to unmanaged memory.
Marshal.StructureToPtr(p, pnt, false);

// Create another point.
Point anotherP;

// Set this Point to the value of the
// Point in unmanaged memory.
anotherP = (Point)Marshal.PtrToStructure(pnt, typeof(Point));

Console.WriteLine("The value of new point is " + anotherP.x + " and " + anotherP.y + ".");

}
finally
{
// Free the unmanaged memory.
Marshal.FreeHGlobal(pnt);
}



}

}