Chapter141:Pointers&UnsafeCode

No Comments

Section141.1:Introductiontounsafecode

C# allows using pointer variables in a function of code block when it is marked by the unsafemodifier. The unsafe code or the unmanaged code is a code block that uses a pointer variable.

A pointer is a variable whose value is the address of another variable i.e., the direct address of the memory location. similar to any variable or constant, you must declare a pointer before you can use it to store any variable address.

Thegeneralformofapointerdeclarationis:

type*var-name;

Following arevalidpointerdeclarations:

int *ip; /*pointertoaninteger*/

double*dp; /*pointertoadouble*/

float*fp; /*pointertoafloat*/

char*ch /*pointertoacharacter*/

ThefollowingexampleillustratesuseofpointersinC#,usingtheunsafemodifier:

usingSystem;

namespaceUnsafeCodeApplication

{

classProgram

{

staticunsafevoidMain(string[]args)

{

intvar=20;

int*p=&var;

Console.WriteLine(“Data is:{0}”,      var);

Console.WriteLine(“Addressis:{0}”,           (int)p);

Console.ReadKey();

}

}

}

Whentheabovecodewasscompiledandexecuted,itproducesthefollowingresult:

Data is: 20

Address is: 99215364

Insteadofdeclaringanentiremethodasunsafe,youcanalsodeclareapartofthecodeasunsafe:

//safecode

unsafe

{

//youcanusepointershere

}

//safecode

Section141.2:AccessingArrayElementsUsingaPointer

InC#,anarraynameandapointertoadatatypesameasthearraydata,arenotthesamevariabletype.For example,int*pandint[]p,arenotsametype.Youcanincrementthepointervariablepbecauseitisnotfixedin memorybutanarrayaddressisfixedinmemory,andyoucan’tincrementthat.

Therefore,ifyouneedtoaccessanarraydatausingapointervariable,aswetraditionallydoinC,orC++,youneed to fix the pointer using the fixed keyword.

The following example demonstrates this:

usingSystem;

namespaceUnsafeCodeApplication

{

classTestPointer

{

publicunsafestaticvoidMain()

{

int[]     list={10,100,200};

fixed(int*ptr=list)

/*letushavearrayaddressinpointer*/

for(inti=0;i<3;i++)

{

Console.WriteLine(“Addressoflist[{0}]={1}”,i,(int)(ptr+i));

Console.WriteLine(“Valueoflist[{0}]={1}”,i,*(ptr+i));

}

Console.ReadKey();

}

}

}

Whentheabovecodewascompiledandexecuted,itproducesthefollowingresult:

Addressoflist[0]=31627168 Value

of list[0] = 10

Addressoflist[1]=31627172

Value of list[1] = 100

Addressoflist[2]=31627176

Value of list[2] = 200

Section141.3:CompilingUnsafeCode

Forcompilingunsafecode,youhavetospecifythe/unsafecommand-lineswitchwithcommand-linecompiler.

For example, to compile a program named prog1.cs containing unsafe code, from command line, give the command:

csc/unsafeprog1.cs

IfyouareusingVisualStudioIDEthenyouneedtoenableuseofunsafecodeintheprojectproperties.

Todothis:

  • Open project properties by double clicking the properties node in the Solution Explorer.
  • Click on the Build tab.
  • Select the option “Allow unsafe code”

Section141.4:RetrievingtheDataValueUsingaPointer

You can retrieve the data stored at the located referenced by the pointer variable, using the ToString() method. The following example demonstrates this:

usingSystem;

namespaceUnsafeCodeApplication

{

classProgram

{

publicstaticvoidMain()

{

unsafe

{

intvar=20;

int*p=&var;

Console.WriteLine(“Datais:{0}”,var);

Console.WriteLine(“Datais:{0}”,p->ToString());

Console.WriteLine(“Addressis:{0}”,(int)p);

}

Console.ReadKey();

}

}

}

Whentheabovecodewascompiledandexecuted,itproducesthefollowingresult:

Data is: 20

Data is: 20

Address is: 77128984

Section141.5:PassingPointersasParameterstoMethods

Youcanpassapointervariabletoamethodasparameter.Thefollowingexampleillustratesthis:

usingSystem;

namespaceUnsafeCodeApplication

{

classTestPointer

{

publicunsafevoidswap(int*p,int*q)

{

inttemp=*p;

*p=*q;

*q=temp;

}

publicunsafestaticvoidMain()

{

TestPointerp=newTestPointer();

intvar1=10;

intvar2=20;

int*x=&var1;

int*y=&var2;

Console.WriteLine(“BeforeSwap:var1:{0},var2:{1}”,var1,var2); p.swap(x,y);

Console.WriteLine(“AfterSwap:var1:{0},var2:{1}”,var1,var2); Console.ReadKey();

}

}

}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:

Before Swap: var1: 10, var2: 20

After Swap: var1: 20, var2: 10

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Recent Posts

Leave a Comment