Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem with this is that the C# marshaller passes a temporary block of memory into the function as <code>aName</code>. This memory is the destroyed when the function returns. But you are also asking the C# marshaller to marshal this same block of memory into a C# string.</p> <p>It's not good practice to return a null-terminated string from a native DLL function anyway. You have a couple of options:</p> <ol> <li>Use a <code>StringBuilder</code> on the C# side to pre-allocate the memory for the string. This requires you to get hold of the required size somehow. This is the most common way to interop strings.</li> <li>Return the string as a COM <code>BSTR</code> and the C# marshaller knows how to marshall and dispose a <code>BSTR</code>, and has access to the COM allocator to do so. I have no knowledge about using <code>BSTR</code> in FreePascal but in Delphi you simply use <code>WideString</code>. You also need to tell the C# marshaller that you are returning a <code>BSTR</code>.</li> </ol> <p>I personally have a preference for option 2. There is one wrinkle though and that is that different compilers use a different ABI for function return values, as discussed at this question: <a href="https://stackoverflow.com/questions/9349530/why-can-a-widestring-not-be-used-as-a-function-return-value-for-interop">Why can a WideString not be used as a function return value for interop?</a> The easy way around that is to return the string in a parameter rather than using the function return value.</p> <p>The code looks like this:</p> <p><strong>Pascal</strong></p> <pre><code>procedure Encrypt(Input: WideString; out Output: WideString); stdcall; begin Output := Input; end; </code></pre> <p><strong>C#</strong></p> <pre><code>[DllImport("project1.dll")] public static extern void Encrypt( [MarshalAs(UnmanagedType.BStr)] string input; [MarshalAs(UnmanagedType.BStr)] out string output ); </code></pre>
 

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