xsharp.eu • Casting, dereferencing & C.
Page 1 of 1

Casting, dereferencing & C.

Posted: Thu Jun 03, 2021 12:55 pm
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

Casting, dereferencing & C.

Posted: Thu Jun 03, 2021 1:55 pm
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

Casting, dereferencing & C.

Posted: Thu Jun 03, 2021 3:10 pm
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

Casting, dereferencing & C.

Posted: Thu Jun 03, 2021 3:36 pm
by antonello.negrone
Robert & Leonid, thank you, that does the trick!