Casting, dereferencing & C.

We encourage new members to introduce themselves here. Get to know one another and share your interests.
Post Reply
antonello.negrone
Posts: 22
Joined: Tue May 03, 2016 8:57 am
Location: Italy

Casting, dereferencing & C.

Post by antonello.negrone »

The following test lines of code in VO always return 5, instead in X# dont' work as expected:

Code: Select all

FUNCTION Start( ) AS VOID
	LOCAL DIM p[4]	AS BYTE 

	p[1]	:=	5
	System.Console.WriteLine( AsString( DWORD(@p[1])))    //strange results
	System.Console.WriteLine( Bin2DW(Mem2String( @p[1],4)) )   //correct result
RETURN
The output of "strange results" line is alway different at each run, the second is always correct.
The test app is compiled in VO dialect with /unsafe + /vo7

TIA for the help
Antonello
User avatar
robert
Posts: 4258
Joined: Fri Aug 21, 2015 10:57 am
Location: Netherlands

Casting, dereferencing & C.

Post by robert »

Antonello,

You are probably expecting that

Code: Select all

DWORD(@p[1])
will take the address of @P[1] and treat that like a DWORD PTR and you want to dereference that pointer and get the DWORD value at that location.

However the DWORD( something ) code in VO can mean 2 things:

- derefence a pointer
- convert the value to a DWORD

X# is doing the second in this case and therefore gives you the address as a DWORD. Each time you run the app that address is different.

I would recommend to do something like this instead (untested)

Code: Select all

LOCAL dwptr as DWORD PTR
dwptr := @p[1]    // you can probably also do dwptr := @p
System.Console.WriteLine( AsString( dwptr[1]))
Robert
XSharp Development Team
The Netherlands
robert@xsharp.eu
leon-ts
Posts: 429
Joined: Fri Feb 03, 2017 1:43 pm

Casting, dereferencing & C.

Post by leon-ts »

Antonello,

You just need to "tell" the compiler that in this context you mean a pointer, not a pointer value. To do this, it is enough to cast to the PTR type:

Code: Select all

System.Console.WriteLine( AsString( DWORD( (PTR)@p[1] ) ) )
Best regards,
Leonid
Best regards,
Leonid
antonello.negrone
Posts: 22
Joined: Tue May 03, 2016 8:57 am
Location: Italy

Casting, dereferencing & C.

Post by antonello.negrone »

Robert & Leonid, thank you, that does the trick!
Post Reply