作为函数参数,从Delphi传递到C#时,空字符串变为空 [英] Empty string becomes null when passed from Delphi to C# as a function argument

查看:297
本文介绍了作为函数参数,从Delphi传递到C#时,空字符串变为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个本机Delphi exe,通过COM互操作调用C#dll。这是演示此问题的最简单的例子:



Delphi:

  IClass1 = interface(IDispatch)
['{B29BAF13-E9E4-33D7-9C92-FE28416C662D}']
函数Test(const aStr:WideString):WideString;安全套
结束

var
obj:IClass1;
s:string;
begin
obj:= CoClass1.Create as IClass1;
s:= obj.Test(''); //返回'[null]'
end;

C#:

 code> [ComVisible(true)] 
public interface IClass1
{
string Test(string aStr);
}

[ComVisible(true)]
public class Class1:IClass1
{
public string Test(string aStr)
{
if(aStr == null)return[null];
if(aStr ==)return[empty];
returnnot empty:+ aStr;
}
}

当我在Delphi中调用一个空字符串的方法Test ,C#部分作为参数值接收null。这是为什么?不应该是空字符串吗?

解决方案

在Delphi中, AnsiString UnicodeString WideString 值由 nil 指针,当它们为空。 COM使用 BSTR 作为字符串。 Delphi包裹 BSTR WideString 。所以没有办法将一个空的非nil字符串传递给一个COM方法,它需要一个 WideString 作为参数,它将为 nil


I have a native Delphi exe which calls into C# dll via COM interop. Here's the simplest case which demonstrate this issue:

Delphi:

IClass1 = interface(IDispatch)
  ['{B29BAF13-E9E4-33D7-9C92-FE28416C662D}']
  function Test(const aStr: WideString): WideString; safecall;
end;

var
  obj: IClass1;
  s: string;
begin
  obj := CoClass1.Create as IClass1;
  s := obj.Test('');  // Returns '[null]'
end;

C#:

[ComVisible(true)]
public interface IClass1
{
    string Test(string aStr);
}

[ComVisible(true)]
public class Class1 : IClass1
{
    public string Test(string aStr)
    {
        if (aStr == null) return "[null]";
        if (aStr == "") return "[empty]";
        return "Not empty: " + aStr;
    }
}

When I call method Test with an empty string in Delphi, the C# part receives null as a parameter value. Why is that? Shouldn't it be an empty string also?

解决方案

In Delphi, AnsiString, UnicodeString, and WideString values are represented by a nil pointer when they are empty. COM uses BSTR for strings. Delphi wraps BSTR with WideString. So there is no way to pass an "empty" non-nil string to a COM method that takes a WideString as a parameter, it will be nil instead.

这篇关于作为函数参数,从Delphi传递到C#时,空字符串变为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆