Page 1 of 1

C <-> ASM

Posted: Sat Jan 24, 2015 6:09 pm
by Hialmar
When you call some ASM from C, the parameters are on the stack and you use code like this to get them:

Code: Select all

	ldy #0
	lda (sp),y ; address lo
	sta tmp0
	iny
	lda (sp),y ; address hi
	sta tmp0+1
       ...
But for returning data, I thought you had to put the low byte in A and the high byte in X but it looks like it is the reverse.
Or is it that when returning a single byte (a char for example) you need to put it in X ?

Can someone explain this to me ?

Thanks.

Re: C <-> ASM

Posted: Sat Jan 24, 2015 8:31 pm
by iss
With OSDK to return 0x1234:

Code: Select all

lda #$12
ldx #$34
rts
to return 1 byte use register X.

The same thing when using CC65 is the opposite

Code: Select all

ldx #$12
lda #$34
rts
to return 1 byte use register A.

So, both are correct but depending what tool-chain is used ;)

Re: C <-> ASM

Posted: Sat Jan 24, 2015 10:27 pm
by Hialmar
Ah ok thanks a lot :)

Re: C <-> ASM

Posted: Sun Jan 25, 2015 8:04 am
by coco.oric
@iss :
As the low and high values are inverted on rts assembler routine, can you tell us if it the same way to pass parameters from osdk to ass compared to cc65 to assembler code.

Re: C <-> ASM

Posted: Sun Jan 25, 2015 8:45 am
by Hialmar
I suppose that on the stack values are stored in Little Endian mode as is normal for a 6502.

The thing is that there is no order in registers so telling that X is before A or the reverse is only a matter of arbitrary choice.

Re: C <-> ASM

Posted: Sun Jan 25, 2015 7:50 pm
by iss
Passing parameters from C to assembler is the same in OSDK and CC65.
Parameters can be accessed using the stack pointer sp in the same way in OSDK and CC65.
Note: sp is NOT the processor's stack pointer (i.e. the one in memory range $100-$1FF)!

The only difference is that in CC65 you have to properly align the 'sp' before returning from the assembler routine.
For this are predefined functions 'incsp1', 'incsp2', 'incsp3'. etc. The number represents the sum of all parameters in bytes.