Writing the contents of a Memory Location (intPtr) to a text file  
Author Message
Jith





PostPosted: Visual C# General, Writing the contents of a Memory Location (intPtr) to a text file Top

How can i write the contents of a Memory location to which i have a pointer(intptr) to a text file The memory location contains the data in a structure...i just want to see the contents char by char..Could some one plz tell me how i can achieve this using C#

Thanks

Jith



Visual C#16  
 
 
Alex Farber





PostPosted: Visual C# General, Writing the contents of a Memory Location (intPtr) to a text file Top

Suppose you have two variables:

IntPtr ptr;   // pointer
int size;      // number bytes in the memory block

Code:

Byte[] byteArray = new Byte[ n ];
Marshal.Copy(ptr, byteArray, 0, n);

Now all bytes from unmanaged memory block are copied to byteArray, and you can to handle this array by the way you need.


 
 
Jith





PostPosted: Visual C# General, Writing the contents of a Memory Location (intPtr) to a text file Top

Hi Alex,

Thanks a lot for the quick reply Alex..That really helped...

Regards

Jith


 
 
Jith





PostPosted: Visual C# General, Writing the contents of a Memory Location (intPtr) to a text file Top

I am just adding this function so that others can use it if needed...

public static void WriteToFile(IntPtr iPtr,int size,string sFileName)

{

if(sFileName.Trim().Length == 0)

sFileName = ;

Byte[] Contents = new Byte[size];

Marshal.Copy(iPtr, Contents, 0, size);

System.IO.FileStream fs = new System.IO.FileStream(sFileName , System.IO.FileMode.Create);

foreach (Byte bt in Contents)

fs.WriteByte(bt);

fs.Flush();

fs.Close();

}