views:

778

answers:

1

I have a Delphi 7 dll that exports the following function:

function StringTest(var StringOut : pchar) : boolean; stdcall;

begin
    GetMem(StringOut, 100);
    StrPCopy(StringOut, 'Test output string.');
    result := true;
end;

This function is imported in C# as follows:

[DllImport(@"C:\\Test\\DelphiTest.dll")]
public static extern bool StringTest(out string stringOut);

When I call the import from a WPF app it works fine and I see my test string returned in the out parameter. When I attempt the same thing from a site hosted in Cassini it works fine as well. However, when I run that method from a site hosted in IIS7 it fails. If I comment out the GetMem and StrPCopy lines the function returns "true" in IIS. How can I get some string data back into C# from Delphi in a site hosted in IIS?

+4  A: 

This is not how 'normal' dll functions return strings. It is unclear in your code who should free the string. Maybe that is the reason .Net doesn't always like it. The caller should allocate enough memory to put the result string in.

function StringTest(const StringOut : pchar; MaxLen: Integer) : Boolean; stdcall;
begin
    StrPLCopy(StringOut, 'Test output string.', MaxLen);
    result := true;
end;

[DllImport(@"C:\\Test\\DelphiTest.dll", CharSet = CharSet.Ansi)]
public static extern bool StringTest(ref string stringOut, int maxLen);
Lars Truijens