开发者

Exposing unmanaged const static std::string in a managed C++ class

开发者 https://www.devze.com 2022-12-11 16:50 出处:网络
I have a non-.NET C++ class as follows: Foo.h: namespace foo { const static std::string FOO; ... } Foo.cc: using namespace foo;

I have a non-.NET C++ class as follows:

Foo.h:

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

Foo.cc:

using namespace foo;

const std::string FOO = "foo";

I want to expose this for use in a C# application, but I keep getting errors about mixed types when I try the following:

FooManaged.h:

namespace foo {
  namespace NET {
    public ref class Foo {开发者_如何学Go
      public:
        const static std::string FOO;
    }
  }
} 

FooManaged.cc:

using namespace foo::NET;

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

What's the right way to translate an unmanaged string constant to a managed string constant?


In C++/CLI, the literal keyword is used in place of static const where you want the constant definition to be included in the interface exposed to fully managed applications.

public:
    literal String^ Foo = "foo";

Unfortunately, literal requires an immediate value, so using the std::string value is not possible. As an alternative, you can create a static read-only property that returns the string.

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

Personally, I believe rewriting the string again and using literal is the better option. However, if you are highly concerned about the constant changing (in a newer version, for example), the property will use the version of FOO in the native library.

0

精彩评论

暂无评论...
验证码 换一张
取 消