我的托管 C++ DLL 中有一个在编译时计算的 const int。我需要在调用它的 C# 程序中的一个属性中使用这个值。最初我创建了一个返回 const int 值的静态方法,但 C# 没有将其视为编译时常量。我还尝试在 DLL 命名空间中将其声明为 const int
// C++
namespace MyNameSpace {
const int AttributeConstValue = 15 + sizeof(int);
. . .
}
尝试从 C# 访问 MyNameSpace.AttributeConstValue 返回“命名空间 MyNameSpace 中不存在”
有没有办法将 const 传递给 C# 并将其视为 const 表达式?
最佳答案
您必须使用 C++/CLI literal 关键字来声明对其他托管编译器可见的公共(public)常量。它必须出现在 ref 类中。像这样:
namespace Example {
public ref class Constants {
public:
literal int AttributeConstValue = 15 + sizeof(int);
};
}
示例 C# 用法:
[MyAttribute(Example.Constants.AttributeConstValue)]
// etc..
请注意,这是相当危险的。文字值被编译到 C# 程序集的元数据中,而不引用您的 C++/CLI 程序集。因此,如果您更改此声明但不 重新编译 C# 项目,那么您将遇到严重的不匹配。但只要您需要在属性声明中使用它,就没有解决办法。
关于c# - 如何将 const int 从托管 C++ DLL 传递到 C# 以用作属性中的字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11213983/