【问题标题】:C# PInvoke Delphi dll that returns a string fails in IIS only返回字符串的 C# PInvoke Delphi dll 仅在 IIS 中失败
【发布时间】:2009-03-24 13:51:08
【问题描述】:

我有一个导出以下函数的 Delphi 7 dll:

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

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

这个函数在C#中导入如下:

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

当我从 WPF 应用程序调用导入时,它工作正常,我看到我的测试字符串在 out 参数中返回。当我从 Cassini 托管的站点尝试相同的操作时,它也可以正常工作。但是,当我从 IIS7 中托管的站点运行该方法时,它会失败。如果我注释掉 GetMem 和 StrPCopy 行,该函数在 IIS 中返回“true”。如何在 IIS 中托管的站点中从 Delphi 将一些字符串数据返回到 C#?

【问题讨论】:

  • 您确实应该更具体地了解错误的性质。简单地说“它失败了”并不能告诉任何人任何事情。

标签: c# delphi iis pinvoke


【解决方案1】:

这不是“正常”的 dll 函数返回字符串的方式。您的代码中不清楚谁应该释放字符串。也许这就是.Net 并不总是喜欢它的原因。调用者应该分配足够的内存来放入结果字符串。

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    相关资源
    最近更新 更多