【问题标题】:Exposing unmanaged const static std::string in a managed C++ class在托管 C++ 类中公开非托管 const static std::string
【发布时间】:2015-03-10 01:08:13
【问题描述】:

我有一个非 .NET C++ 类如下:

Foo.h:

namespace foo {
  const static std::string FOO;
  ...
}

Foo.cc:

using namespace foo;

const std::string FOO = "foo";

我想公开它以在 C# 应用程序中使用,但是当我尝试以下操作时,我不断收到有关混合类型的错误:

FooManaged.h:

namespace foo {
  namespace NET {
    public ref class Foo {
      public:
        const static std::string FOO;
    }
  }
} 

FooManaged.cc:

using namespace foo::NET;

const std::string Foo::FOO = foo::FOO;

将非托管字符串常量转换为托管字符串常量的正确方法是什么?

【问题讨论】:

  • 您在 Foo.h 中错误地声明了变量。它必须是非static 并使用extern 声明。

标签: c++-cli managed-c++


【解决方案1】:

在 C++/CLI 中,literal 关键字用于代替 static const,您希望常量定义包含在向完全托管应用程序公开的接口中。

public:
    literal String^ Foo = "foo";

不幸的是,literal 需要立即数,因此无法使用 std::string 值。作为替代方案,您可以创建一个返回字符串的静态只读属性。

public:
    static property String^ Foo
    {
        String^ get()
        {
            return gcnew String(Foo::FOO.c_str()); 
        }
    }

就个人而言,我相信再次重写字符串并使用literal 是更好的选择。但是,如果您高度关注不断变化(例如在较新的版本中),该属性将使用原生库中的 FOO 版本。

【讨论】:

    猜你喜欢
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 2018-03-19
    • 2011-11-23
    相关资源
    最近更新 更多