gpt4 book ai didi

c++-cli - 在托管 C++ 类中公开非托管 const static std::string

转载 作者:行者123 更新时间:2023-12-04 07:01:36 24 4
gpt4 key购买 nike

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

富.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;

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

最佳答案

在 C++/CLI 中,literal使用关键字代替 static const您希望常量定义包含在暴露给完全托管应用程序的接口(interface)中。

public:
literal String^ Foo = "foo";

不幸的是, literal需要立即数,因此使用 std::string值(value)是不可能的。作为替代方案,您可以创建一个返回字符串的静态只读属性。
public:
static property String^ Foo
{
String^ get()
{
return gcnew String(Foo::FOO.c_str());
}
}

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

关于c++-cli - 在托管 C++ 类中公开非托管 const static std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1760637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com