【问题标题】:C++/CLI and .NET out string paramterC++/CLI 和 .NET 输出字符串参数
【发布时间】:2017-08-07 23:10:49
【问题描述】:

在C#中,我有这个方法(.net framework 2.0)

 public String Authenticate( String configUrl, out String tokenId)

我想从托管 c++ 代码中调用它 我有

__authenticator->Authenticate(  gcnew System::String(hostUrl),gcnew System::String(temp));

但 tokenId 会返回为真。

我已经看到一些关于在 C# 中使用 ^ % 的答案,但这就是无法编译。

【问题讨论】:

  • http://stackoverflow.com/a/187577/613130...但是这里有什么问题? temphostUrl 是什么?你期待什么?

标签: c# c++-cli


【解决方案1】:

public String Authenticate(String configUrl, out String tokenId)

这个

__authenticator->Authenticate(
    gcnew System::String(hostUrl),
    gcnew System::String(temp)
);

在 C# 中等同于(考虑到 Authenticate 的签名)

__authenticator.Authenticate(
    new String(hostUrl),
    out new String(temp)
);

但在 C# 中你不能做 out new Something,你只能 out 到变量、字段...所以在 C# 中你需要这样做:

String temp2 = new String(temp);

__authenticator.Authenticate(
    new String(hostUrl),
    out temp2
);

并且,考虑到参数在out 中,您可以:

String temp2;

__authenticator.Authenticate(
    new String(hostUrl),
    out temp2
);

现在,在 C++/CLI 中,您拥有

System::String^ temp2 = gcnew System::String(temp);

__authenticator->Authenticate(
    gcnew System::String(hostUrl),
    temp2
);

或者,知道temp2out(注意refout 之间的区别仅由C# 编译器检查,而不是由C++/CLI 编译器检查)

// agnostic of the out vs ref
System::String^ temp2 = nullptr;

// or knowing that temp2 will be used as out, so its value is irrelevant
// System::String^ temp2;

__authenticator->Authenticate(
    gcnew System::String(hostUrl),
    temp2
);

【讨论】:

    【解决方案2】:

    好的,我知道了,把我传入的参数变成一个字符串^

    CString hostUrl;
    String^ temp ;
    String^ error = __authenticator.get() == nullptr ? "failed to get token" : 
                     __authenticator->Authenticate(  gcnew System::String(hostUrl),temp);
    

    【讨论】:

      猜你喜欢
      • 2021-07-15
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多