1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace Pointers { unsafe class Program { static unsafe void Main( string[ ] args ) { Unsafe unsafeObject = new Unsafe( 1, 2, 3, 4 ); Console.WriteLine( "FirstLocation[ " + unsafeObject.firstLocation->ToString( ) + " ]\n" + "SecondLocation[ " + unsafeObject.secondLocation->ToString( ) + " ]" ); Console.Read( ); } } unsafe struct Unsafe { public Safe* firstLocation, secondLocation; public Unsafe( int fl_x, int fl_y, int sl_x, int sl_y ) { Safe ffl = new Safe( fl_x, fl_y ), fsl = new Safe( sl_x, sl_y ); this.firstLocation = &ffl; this.secondLocation = &fsl; } } struct Safe { public int x, y; public Safe( int x, int y ){ this.x = x; this.y = y; } public override string ToString( ) { return this.x + "," + this.y; } } }
Expected output
1 2 3
FirstLocation[ 1,2 ] SecondLocation[ 3,4 ]
Given output
1 2
FirstLocation[ 14,67169456 ] SecondLocation[ 19593296,19593248 ]
Refactorings
No refactoring yet !
Andre Steenveld
May 8, 2008, May 08, 2008 09:00, permalink
I have found the problem. It appears that pointers to objects that are declared in the scope of a function don't stay alive after the function has returned. This other than in javascript for example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace Pointers { class Program { unsafe static void Main( string[ ] args ) { Unsafe unsafeObject = new Unsafe( 1, 2, 3, 4 ); Console.WriteLine( "FirstLocation[ " + unsafeObject.firstLocation->ToString( ) + " ]\n" + "SecondLocation[ " + unsafeObject.secondLocation->ToString( ) + " ]" ); Console.Read( ); } } unsafe struct Unsafe { public Safe* firstLocation, secondLocation; private Safe sfLocation, ssLocation; public Unsafe( int fl_x, int fl_y, int sl_x, int sl_y) { this.sfLocation = new Safe( fl_x, fl_y ); this.ssLocation = new Safe( sl_x, sl_y ); fixed( Safe* fl = &this.sfLocation ) fixed( Safe* sl = &this.ssLocation ) { this.firstLocation = fl; this.secondLocation = sl; } } } struct Safe { public int x, y; public Safe( int x, int y ){ this.x = x; this.y = y; } public override string ToString( ) { return this.x + "," + this.y; } } }
I am trying to work out how unmanged objects work in C# but for some reason it looks like my objects arn't properly initized. Could someone help me out here?