English 中文(简体)
Exposing unmanaged const static std::string in a managed C++ class
原标题:

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?

问题回答

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.





相关问题
Compiler can t find structures, what should i be including

UPDATE: I thought it was Windsows.h i need to include and you have confirmed this, but when i do include it i get a bunch of messages like the following... 1>C:Program FilesMicrosoft SDKs...

Cast native pointer to a C++CLI managed object reference?

I have a callback that is called through a delegate. Inside it I will need to treat the buffer data that arrive from a record procedure. Normally in a unmanaged context I could do a reinterpret_cast ...

gcnew KeyEventHandler compile problem (VC++)

My managed c++ code fails to compile with the error message .Window.cpp(11) : error C2440: initializing : cannot convert from System::Windows::Forms::Form ^ to Enviroment::Window ^ No ...

The speed of .NET in numerical computing

In my experience, .NET is 2 to 3 times slower than native code. (I implemented L-BFGS for multivariate optimization). I have traced the ads on stackoverflow to http://www.centerspace.net/products/ the ...

Creating 64 bit CLR C++ projects in VS2008

I am creating a wrapper around a native lib, which comes in both 32 & 64 bit flavors. I have a fairly complex C++/CLR project that includes a number of header files from the native libs. I got it ...

热门标签