[fpc-pascal] Access to RS232 ports with fpc

Martin lazarus at mfriebe.de
Sun Nov 1 22:32:47 CET 2009


Holger Bruns wrote:
> Jürgen Hestermann schrieb:
>>> function SerRead(Handle: TSerialHandle; var Buffer; Count: LongInt): 
>>> LongInt;
>>>    begin
>>>    Result := fpRead(Handle, Buffer, Count);
>>>    end;
>>> i don't understand the declaration for "buffer" in the function 
>>> below, because no type is declared for "buffer". 
>>
>> I believe that the type is irrelevant, you can use whatever you want. 
>> I think that it's just used by fpRead to buffer data. You only 
>> provide the space for the buffer but you don't need to read it 
>> directly. It seems that Count has to be the size of the buffer. But I 
>> am just guessing....
> My hope was to read more than guessing. As I pointed out, the "buffer" 
> seems not to be filled with incoming data from the selected serial 
> port. Hence I cannot read just this data, and serread seems to be 
> faulty. For this reason I ask for an advice. I need to look on working 
> sample code to use this function in a working manner. In my example, 
> serread replies only, what has been written with serwrite right 
> before. Not even serflush, executed right after serwrite, can solve 
> this problem to me.

var foo;
const foo;

are hidden pointer types.
That is foo would contain a pointer, but you never see this. You never 
have to get the address of something, and you never have to dereference it.

As for using this:

SerRead(Handle, Buffer, 0)

Buffer must be the first byte of a block of memory

you can do:
var buffer: Array of byte;

SetLength(Buffer, 1000);
SerRead(Handle, Buffer[0], 1000);

NOTE the [0] index you supply the first byte of your buffer.
FPC is internally taking the address of this first bytes, and then 1000 
bytes from this address on will be used

----
Example 2

var buffer: ^Byte; // bointer to byte

Buffer = GetMem.....; // buffer contains the address of your memory
SerRead(Handle, Buffer^, 1000); // again ^ dereference it

----
Example 3
There are case where the [0] or ^ is optional, but you need to 
understand a lot how fpc allocates memory

var buffer: Array [0..999] of byte;

SerRead(Handle, Buffer, 1000); // you can do buffer[0] too

-------

The most common fault is, that people forget to specify [0] or ^ and 
that leads to errors.

The below is WRONG:
var buffer: ^Byte; // bointer to byte

Buffer = GetMem.....; // buffer contains the address of your memory
SerRead(Handle, Buffer, 1000); // missing ^

It is wrong because buffer itself is a variable having 4 or 8 byte (32 
or 64 bit platform). Buffer only contains the address of where the data is.
If you pass buffer like in the example above, "SerRead" willbut the 
rsult into the 4 bytes of the variable itself (and then writing to 
random memory behind this)


Martin










More information about the fpc-pascal mailing list