gpt4 book ai didi

c++ - SWIG 不可变 std::map 引用

转载 作者:行者123 更新时间:2023-11-30 05:48:29 25 4
gpt4 key购买 nike

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

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

我有另一个返回 const TestClassMap& 的类.

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

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

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

但是,在 C# 库中,返回 const TestClassMap& 的函数实际上返回一个可以更改(可变)的 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.

关于c++ - SWIG 不可变 std::map 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28156082/

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