Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To convert <code>PWideChar</code> to <code>AnsiString</code>:</p> <pre><code>function WideCharToAnsiString(P: PWideChar): AnsiString; begin Result := P; end; </code></pre> <p>The code converts from UTF-16, null-terminated PWideChar to <code>AnsiString</code>. If you are getting question marks in the output then either your input is not UTF-16, or it contains characters that cannot be encoded in your ANSI codepage.</p> <p>My guess is that what is actually happening is that your Delphi DLL was created with a pre-Unicode Delphi and so uses ANSI text. But now you are trying to link to it from a post-Unicode Delphi where <code>PChar</code> has a different meaning. I'm sure Rob explained this to you in your other question. So you can simply fix it by declaring your DLL import to return <code>PAnsiChar</code> rather than <code>PChar</code>. Like this:</p> <pre><code>function GetDeviceChannelInfo_HSI(PortNumber, Address, ChNumber: Integer; var State: Integer): PAnsiChar; stdcall; external DLL_FILENAME; </code></pre> <p>And when you have done this you can assign to a string variable in a similar vein as I describe above.</p> <p>What you need to absorb is that in older versions of Delphi, <code>PChar</code> is an alias for <code>PAnsiChar</code>. In modern Delphi it is an alias for <code>PWideChar</code>. That mismatch would explain everything that you report.</p> <hr> <p>It does occur to me that writing a Delphi wrapper to the DLL and communicating via stdout with your C# app is a very roundabout approach. I'd just p/invoke the DLL directly from the C# code. You seem to think that this is not possible, but it is quite simple.</p> <pre><code>[DllImport(@"mydll.dll")] static extern IntPtr GetDeviceChannelInfo_HSI( int PortNumber, int Address, int ChNumber, ref int State ); </code></pre> <p>Call the function like this:</p> <pre><code>IntPtr ptr = GetDeviceChannelInfo_HSI(Port, Addr, Channel, ref State); </code></pre> <p>If the function returns a UTF-16 string (which seems doubtful) then you can convert the <code>IntPtr</code> like this:</p> <pre><code>string str = Marshal.PtrToStringUni(ptr); </code></pre> <p>Or if it is actually an ANSI string which seems quite likely to me then you do it like this:</p> <pre><code>string str = Marshal.PtrToStringAnsi(ptr); </code></pre> <p>And then of course you'll want to call into your DLL to deallocate the string pointer that was returned to you, assuming it was allocated on the heap.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload