2
votes

In my Delphi code I have to call a DLL's function (written in Visual C) with the following prototype:

int PWFunc(LPCSTR szName, int nWidth, int nHeight, LPCSTR szFileName)

How can I convert Delphi AnsiString variables (for Name and FileName) into right type parameters (LPCSTR szName and szFileName) of function call ? I know that VC LPCSTR type corresponds to Delphi PAnsiChar type, but what is the right procedure to convert AnsiString to PAnsiChar ?

1
PAnsiChar(AnsiString(s)) is the answer to your last Q, assuming the encoding is ANSI. If the encoding is UTF-8, different answer!David Heffernan
@henry, what version of Delphi are you using ? At least in Delphi 2009 there's the LPCSTR type defined...TLama
For UTF-8 encoding, you can pass a parameter value like PAnsiChar(AnsiString(UTF8Encode(s))) or directly LPCSTR(AnsiString(UTF8Encode(s))), if you define the prototype by using LPCSTR data type. Or even without the conversion to AnsiString, like PAnsiChar(UTF8Encode(s)) or LPCSTR(UTF8Encode(s)).TLama
What have you tried, yourself? I'm quite sure your first or second attempt would produce the desired result...Andreas Rejbrand
Show the code on the other side of the interface. Rudy's translation is fine and behaves the same way on all operating systems. So, there's something wrong with the information that we have.David Heffernan

1 Answers

2
votes

LPCSTR and LPSTR correspond to PAnsiChar, so that is what you use:

function PWFunc(szName: PAnsiChar; nWidth, nHeight: Longint;
  szFileName: PAnsiChar): Longint; cdecl { or stdcall, see documentation };
  external 'somedll.dll' name 'PWFunc';

You call it like:

X := PWFunc(PAnsiChar(AnsiString(SomeName)), 17, 33, 
       PAnsiChar(AnsiString(SomeFileName)));

Whether your function is stdcall or dcecl depends on compiler settings. Read the documentation. If in doubt, try both. It looks like cdecl to me, so start with that.