Delphi – Sending Delphi string as a parameter to DLL

delphidllparametersstring

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?

Best Answer

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.