SWIG 不可变 std::map 参考

SWIG immutable std::map reference

我在 C++ 中有一个 typedef,如下所示:

typedef std::map<int, TestClass> TestClassMap;

我还有一个 class returns 一个 const TestClassMap&

然后在我的 SWIG 接口 (.i) 文件中,我有以下内容:

namespace std
{
    %template(TestClassMap) map<int, myNamespace::TestClass>;
}

这可以很好地编译并创建 C# 库。

然而,在C#库中,returns一个const TestClassMap&的函数实际上是returns一个可以改变(可变)的TestClassMap。如果我查看返回对象的 IsReadOnly 设置,它是错误的。

通过查看 SWIG 文档,似乎有一种方法可以将对象标记为 immutable,我认为这是我想要的。但是,我已经尝试这样做并且没有取得任何成功。我尝试了以下各项:

%feature("immutable","1") TestClass;

%immutable TestClass;

%immutable
%template(TestClassMap) map<int, myNamespace::TestClass>;
%mutable

const std::map<>& 不能不可变是否有某些根本原因?还有其他想法吗?

SWIG 不会尝试保持常量正确性。参考文档中的this rant

Although this is clearly a violation of the C++ type-system, fixing the problem doesn't seem to be worth the added implementation complexity that would be required to support it in the SWIG run-time type system. There are no plans to change this in future releases (although we'll never rule anything out entirely).

The bottom line is that this particular issue does not appear to be a problem for most SWIG projects. Of course, you might want to consider using another tool if maintaining constness is the most important part of your project.