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:
Then to call the function, you need to use an Ansi string, and convert it to a PAnsiChar, like so:
(The cast to DWORD is unnecessary.) If you do it like this, it should work without giving you any trouble.