Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Delphi string as a parameter to DLL

I want to call a DLL function in Delphi 2010. This function takes a string and writes it to a printer with an USB interface. I do not know in which language is the DLL developed. According to the documentation, the syntax of the function is:

int WriteUSB(PBYTE pBuffer, DWORD nNumberOfBytesToWrite);

How can I declare and use my function in Delphi?

I declare the function like this:

var
function WriteUSB(myP:pByte;n:DWORD): integer ; external 'my.dll';

Should I use stdcall or cdecl in the declaration?

I call the DLL function like this:

procedure myProc;
var 
   str : string:
begin
     str := 'AAAAAAAAAAAAAAAAAAAAA';
     WriteUSB(str,DWORD(length(tmp)));
end;

But this code give me exception all the time. I know that the problem is that String is Unicode and each character > 1 byte. I tried to convert to different string types ( AnsiChar and ShortString) but I failed.

What is the correct way to do this?

like image 540
amin Avatar asked Jul 23 '10 02:07

amin


1 Answers

A couple things. First off, if this is a C interface, which it looks like it is, then you need to declare the import like this:

function WriteUSB(myP:pAnsiChar; n:DWORD): integer; cdecl; external 'my.dll';

Then to call the function, you need to use an Ansi string, and convert it to a PAnsiChar, like so:

procedure myProc;
var 
   str : AnsiString;
begin
     str := 'AAAAAAAAAAAAAAAAAAAAA';
     WriteUSB(PAnsiChar(str), length(str));
end;

(The cast to DWORD is unnecessary.) If you do it like this, it should work without giving you any trouble.

like image 51
Mason Wheeler Avatar answered Oct 11 '22 14:10

Mason Wheeler