Pointers, DLL Header files and lots of exceptions?

From: Kevin Oleniczak (kevinoleniczak_at_comcast.net)
Date: 08/25/04


Date: Tue, 24 Aug 2004 23:08:03 -0500

I've spent a few days trying to get a piece of my app that calls functions
in a DLL to work correctly. I have the C header file that I used Dr. Bob's
program on to convert to a Delphi unit. That worked ok... I think, but
question the data type conversion it does as well as the method to access
the data.

Here's a snipit of the original header file:

#pragma pack( push, My_Byte_Pack, 1)

DECLSPEC_CLASS int get_values(HANDLE hCom, int* error_count, int*
total_count);

Here's a snippet of the Delphi unit that wraps it:

var get_values: function (hCom: THandle; var error_count: integer; var
total_count: integer): integer cdecl {$IFDEF WIN32} stdcall {$ENDIF};

So I drop 2 buttons and a TMemo on the form. The first calls a function (not
shown) that gets the hCom value to set the HANDLE (a global variable of type
THandle called myHANDLE). That part works just fine and was verified to work
by testing against another function. My problem is in the second button
where I call the get_values function listed above.

procedure TMainForm.Button1Click(Sender: TObject);
var
  myError_Count, myTotal_Count: Integer;
begin
 //this function returns 0 if it was successful
  if get_values(myHANDLE, myError_Count, myTotal_Count) = 0 then
    memo1.lines.append ('Here are the two values: ' +
inttostr(myError_Count) + ' ' + inttostr(myTotal_Count) );
end;

Well the function returns a value of 0 and then proceeds to try to write the
values to the memo box. Instead it throws a EAccessViolation at address
004EBABE in module 'test.exe'. Read of address 000003B8. This happens on the
append line to the memo box. What gets really interesting is that if I
replace the memo line with a call like:

  showmessage('Here are the two values: ' + inttostr(myError_Count) + ' ' +
inttostr(myTotal_Count) );

... this works and shows the correct values. BUT after I click ok on the
message dialog... The click procedure ends and throws a similar
EAccessViolation as before, but at a different address. ?!?!

So my questions are:
1) is the c data type "int*", really convert to "var someparam integer"? The
option I would have thought would work would be a "pInteger".
2) If the function really is working with pointers, then shouldn't my button
code use a pointer type to pass to the function?
3) why does memo1.lines.append throw an exception? Something even stranger
is that i can even change the showmessage call to this...

showmessage('Hello world with no reference to the values returned by the
function!');

this will throw an exception on "end;" as well but at address 00000000.

I've spent many hours investigating this on-line and reading docs on pointer
types. I'm at a complete loss and definitely would appreciate some
assistance.

Thanks!

I