Page 1 of 1

return a value in asm functions

Posted: Tue Apr 06, 2010 12:13 pm
by SkaCahToa
hey, I've just learned some basic asm and c. I've programmed a basic 16bit x86 os, but I'm trying to write a function in asm that'll return a byte.

I want to be able to call the function from c code like this:

Code: Select all

char a;
a = pullFromMemory(0xB000, 0x8000);
The code I have for the asm function right now is:

Code: Select all

	.global _pullFromMemory

;char pullFromMemory (int segment, int address)
_pullFromMemory:
	push bp
	mov bp,sp
	push ds
	mov ax,[bp+4]
	mov si,[bp+6]
	mov ds,ax
	mov cl,[si]
	mov al,cl
	mov al,#0	;we only want Ah returned
	pop ds
	pop bp
	ret
However the code currently isn't working. Any ideas what's going on.

Im under the impression that the data in ah is the return value of the function... or am I mistaken?

Re: return a value in asm functions

Posted: Tue Apr 06, 2010 12:30 pm
by bewing
Well, the easy way to do this would just be to use a far pointer in C.

But otherwise it depends on exactly which compiler you are using for the C part of the code. Usually, return values are in EAX -- that is, you should be putting the byte in AL, not AH.

Re: return a value in asm functions

Posted: Tue Apr 06, 2010 1:35 pm
by qw
(Missed bug.)

Re: return a value in asm functions

Posted: Tue Apr 06, 2010 1:51 pm
by Gigasoft
The bug is that it zeroes AL, not AH. The return value should be in AL. Another bug is that SI is not preserved.

Further improvements would be, use the LDS instruction, and use ESP instead of BP (assuming that the high word of ESP is zero). Or better yet, get a compiler that has far pointers.

Re: return a value in asm functions

Posted: Tue Apr 06, 2010 2:02 pm
by qw
Most 16-bit compilers I know support far pointers.

Re: return a value in asm functions

Posted: Tue Apr 06, 2010 2:25 pm
by bitshifter
Also, where/when are the parameters removed from stack?
For stdcall you should retnw 4 assuming 16bit code...

Re: return a value in asm functions

Posted: Tue Apr 06, 2010 3:35 pm
by Owen
bitshifter wrote:Also, where/when are the parameters removed from stack?
For stdcall you should retnw 4 assuming 16bit code...
Presumably its a cdecl function...