作为函数参数,从Delphi传递到C#时,空字符串变为空 [英] Empty string becomes null when passed from Delphi to C# as a function argument
问题描述
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屋!