views:

382

answers:

1

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 {
      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?

+1  A: 

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.

Zooba