delphitype-conversionocrwidestring

Convert WideString to PWideChar


I use Nicomsoft OCR library to OCR images in Delphi. It is good for my tasks and it has Delphi unit-wrapper so it's easy to use it in Delphi. However, Delphi debugger shows "Range Error" message when I pass empty string as parameter value to some OCR functions. I checked the wrapper code and found that DLL library functions accept PWideChars as parameter but wrapper accepts WideString. Inside of unit-wrapper there is the following conversion:

function CallSomeOCRFunction(a: WideString);
var b: PWideChar;
begin
  b := @a[1];
  CallSomeDLLFunction(b); //passing "b" to DLL function that accepts PWideChar
  //.....

I did some research and discovered that many FAQs offer such conversion, for example: http://www.delphibasics.co.uk/RTL.asp?Name=PWideChar

It works if "a" is not empty string, but for empty string it cause "Range" error. How can I get pointer to first character of WideString variable correctly even if it is empty string? As far as I understand, even if string is empty it must contain zero character and PWideChar variable must point to it.


Solution

  • Use PWideChar() cast as described in the documentation. In your case it would be:

    CallSomeDLLFunction(PWideChar(a));