Subject UDF receiving and returning BLOB (pascal)
Author personalsoft_fabiano
Hi all,

I´m writing an UDF to receive any BLOB and return it as another BLOB,
converted to hexadecimal

Ex: select ps_blob_to_hex(cast('ABC' as blob sub_type 0)) returns a
blob containing '414243'

I used some pieces of code from FreeUDFLib, and almost everything is
working, except for the problem below:

// I´m using these data structures to represent a Firebird BLOB

TISC_BlobGetSegment = function(BlobHandle: PInt; Buffer: PChar;
BufferSize: Long; var ResultLength: Long): Short; cdecl;

TISC_BlobPutSegment = procedure(BlobHandle: PInt; Buffer: PChar;
BufferLength: Short); cdecl;

TBlob = record
GetSegment: TISC_BlobGetSegment;
BlobHandle: PInt;
SegmentCount: Long;
MaxSegmentLength: Long;
TotalSize: Long;
PutSegment: TISC_BlobPutSegment;
end;

// Here is the declaration of the UDF in FB

declare external function ps_blob_to_hex
blob,
blob
returns
parameter 2
entry_point 'blob_to_hex'
module_name 'ps_udf';

// Here is the piece of the function where i think the problem happens

function blob_to_hex(Source: PBlob; Blob: PBlob): PBlob; cdecl; export;
begin
Result := Blob;
<some lines of code>
Result^.PutSegment(Result^.BlobHandle, PCharHex, Len * 2);
end;

// The problem

I have two tables with columns storing binary data. The first is a
CHAR(16), and it stores UUID's. The second is a BLOB SUB_TYPE 0, and
it stores files.

If i select from the first table, where the blob sizes are always 16
bytes, it works:

select
ps_blob_to_hex(cast(a.teste as blob sub_type 0))
from
table1 a

If i select from the second table, where the size of the blobs are
larger, it works just on the some records (i presume the records wich
blob size are below <= 32K). Look at the SQL below:

select
char_length(a.filedata),
char_length(ps_blob_to_hex(a.filedata))
from
ps$fil2 a

It returns:

CHAR_LENGTH CHAR_LENGTH1
76101 21130 -> wrong (returned blob should be twice the size of the
original)
378720 36544 -> wrong
22476 44952 -> RIGHT
33138 740 -> wrong
520980 58920 -> wrong
80399 29726 -> wrong
12668 25336 -> RIGHT
14098 28196 -> RIGHT
334264 13168 -> wrong
30277 60554 -> right

I presume there is something wrong the way i'm sending a pchar
containing the hex string to the destination blob

Result^.PutSegment(Result^.BlobHandle, PCharHex, Len * 2);

I debugged the function and 'PCharHex' is always storing the correct
result for all rows, and also the 'Len' variable is representing the
lenght of the original BLOB.

Do someone have a clue about what can be the problem?

Regards,

Fabiano.