0

I have a Delphi function exported from a DLL, and I'm trying to call it from C# without much luck.

The Delphi function looks like this:

procedure RunMe(text: PWideChar; doc: PWideChar; out resultOne: PWideChar; out resultTwo: PWideChar; out errorText: PWideChar; out warningText: PWideChar); stdcall;

In C# I import the function like this:

[DllImport("delphiLibrary.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
    public static extern void RunMe(string text, string doc,
        out string resultOne, out string resultTwo, out string errorText, out string warningText);

And then call it like this:

var text = "some text";
var doc = "some doc";

RunMe(text, doc, out string resultOne, out string resultTwo, out string errorText, out string warningText);

The error I get is of type System.Runtime.InteropServices.SEHException with message external component has thrown an exception

My guess is something in the function signature is handled wrong, but my adventures on Google/StackOverflow have not led me to any clear answer.

Is PWideChar not a string? I tried various mutations of the solution above, but I'm short of ideas by now.

Update: Differs from Calling a Delphi DLL from a C# .NET application since I don't have the possibility to modify the Delphi-code to use string buffers.

Update2: I don't have the possibility to modify the Delphi code.

9
  • 3
    Use CharSet.Unicode.
    – zed
    Commented Dec 28, 2019 at 13:56
  • 1
    Does this answer your question? Calling a Delphi DLL from a C# .NET application
    – Peter Wolf
    Commented Dec 28, 2019 at 14:51
  • 3
    Probably you can't pinvoke that function. But we can't tell for sure until we know what the protocol of the out parameters is. Your code assumes null terminated strings allocated by the COM allocate CoTaskMemAlloc. I'm guessing you didn't actually do that. And yes, you have to use the correct character set, but that's just going to be the first of your problems. To help you more I'd ideally need to see some me of the Delphi code to see how you handle those out parameters. Commented Dec 28, 2019 at 15:04
  • 1
    @remy changing the charset will resolve that without explicit MarshalAs Commented Dec 28, 2019 at 20:18
  • 1
    Your code assumes that they are allocated with the com allocator and tries to deallo ate them accordingly. Which will lead to errors. In fact they are allocated by the Delphi allocator. If I were you I'd change the Delphi code to use the COM allocator. Commented Dec 30, 2019 at 8:44

0

Browse other questions tagged or ask your own question.