将 unique_ptr 与 boost python 结合使用 - boost::shared_ptr 有效,但 unique_ptr 无效

2024-05-06

这可能与以下问题相同

Boost Python 没有 to_python for std::unique_ptr https://stackoverflow.com/questions/20590205/boost-python-no-to-python-for-stdunique-ptr

但是,我还没有看到回复,也不清楚这是一个“boost-python”问题还是由于我对“std::unique_ptr”的特殊使用 我试图弄清楚为什么在使用“std::unique_ptr []”时更改从 boost::shared_ptr 派生的类会中断编译

下面是我的 boost python 模块,有 2 个可能的“smart_array”类 原始版本基于 boost::shared_array 并且工作正常(如下所示)

当我使用基于 unique_ptr (简单替换)的一个时,我会遇到令人困惑的编译错误。

// Boost Includes ==============================================================
#include <boost/python.hpp>
#include <boost/cstdint.hpp>

#define NO_BOOST
#ifdef NO_BOOST
#include "smart_array.h"
#else
#include "boost_smart_array.h"
#endif
template <class Numeric> class cic {
public:
        smart_array<Numeric> nacc; //! Accumulators
        cic(int s) :  nacc(3) {
                for (int i=0;i<3;i++) nacc[i] = (Numeric)0;
        }
        Numeric interpolate() {         return(nacc[2]);        }
};

// Using =======================================================================
using namespace boost::python;
BOOST_PYTHON_MODULE(cic_double)
{
        class_< cic<double> >("cic_double", init< int >())
                .def("interpolate", &cic<double>::interpolate);
}

-- 智能数组类(原-boost)

#include "boost/shared_array.hpp"
    template<class T> class smart_array : public boost::shared_array<T> {
    public:
            //! Default constructor
            smart_array() {} 
            //! Create an smart_array of size n
            smart_array(long n) : boost::shared_array<T>(new T[n]) {
                    elements = n;
            }
            void resize(long n) { 
                    elements = n;
                    boost::shared_array<T>::reset(new T[n]); 
            }
            long len() const { return(elements); }
    private:
            long elements;
    };

新的-基于unique_ptr

template<class T> class smart_array : public std::unique_ptr<T []> {
 public:
  //! Default constructor
  smart_array() {} 
  //! Create an smart_array of size n
  smart_array(long n) : std::unique_ptr<T []>(new T[n]) {
                elements = n;
  }
  void resize(long n) { 
                elements = n;
                std::unique_ptr<T []>::reset(new T[n]); 
  }
  long len() const { return(elements); }
 private:
  long elements;
};

编译错误

[100%] Building CXX object CMakeFiles/cic_double.dir/py_cic_double.cpp.o
In file included from /Users/user/GitHubStuff/boost_cic_test/py_cic_double.cpp:2:
In file included from /usr/local/include/boost/python.hpp:18:
In file included from /usr/local/include/boost/python/class.hpp:23:
In file included from /usr/local/include/boost/python/object/class_metadata.hpp:11:
In file included from /usr/local/include/boost/python/object/value_holder.hpp:50:
In file included from /usr/local/include/boost/preprocessor/iteration/detail/iter/forward1.hpp:52:
/usr/local/include/boost/python/object/value_holder.hpp:135:11: error: no matching constructor for initialization of 'cic<double>'
        : m_held(
          ^
/usr/local/include/boost/python/object/make_instance.hpp:71:30: note: in instantiation of function template specialization 'boost::python::objects::value_holder<cic<double> >::value_holder<boost::reference_wrapper<const cic<double> > >' requested here
        return new (storage) Holder(instance, x);
                             ^
/usr/local/include/boost/python/object/make_instance.hpp:45:22: note: in instantiation of member function 'boost::python::objects::make_instance<cic<double>, boost::python::objects::value_holder<cic<double> > >::construct' requested here
            Derived::construct(&instance->storage, (PyObject*)instance, x)->install(raw_result);
                     ^
/usr/local/include/boost/python/object/class_wrapper.hpp:29:30: note: in instantiation of function template specialization 'boost::python::objects::make_instance_impl<cic<double>, boost::python::objects::value_holder<cic<double> >, boost::python::objects::make_instance<cic<double>, boost::python::objects::value_holder<cic<double> > > >::execute<const boost::reference_wrapper<const cic<double> > >' requested here
        return MakeInstance::execute(boost::ref(x));
                             ^
/usr/local/include/boost/python/converter/as_to_python_function.hpp:27:72: note: in instantiation of member function 'boost::python::objects::class_cref_wrapper<cic<double>, boost::python::objects::make_instance<cic<double>, boost::python::objects::value_holder<cic<double> > > >::convert' requested here
        convert_function_must_take_value_or_const_reference(&ToPython::convert, 1L);
                                                                       ^
/usr/local/include/boost/python/to_python_converter.hpp:88:22: note: in instantiation of member function 'boost::python::converter::as_to_python_function<cic<double>, boost::python::objects::class_cref_wrapper<cic<double>, boost::python::objects::make_instance<cic<double>, boost::python::objects::value_holder<cic<double> > > > >::convert' requested here
        &normalized::convert
                     ^
/usr/local/include/boost/python/object/class_wrapper.hpp:24:8: note: (skipping 2 contexts in backtrace; use -ftemplate-backtrace-limit=0 to see all)
struct class_cref_wrapper
       ^
/usr/local/include/boost/python/object/class_metadata.hpp:219:25: note: in instantiation of function template specialization 'boost::python::objects::class_metadata<cic<double>, boost::python::detail::not_specified, boost::python::detail::not_specified, boost::python::detail::not_specified>::register_aux2<cic<double>, boost::integral_constant<bool, false> >' requested here
        class_metadata::register_aux2((T*)0, use_callback());
                        ^
/usr/local/include/boost/python/object/class_metadata.hpp:205:25: note: in instantiation of member function 'boost::python::objects::class_metadata<cic<double>, boost::python::detail::not_specified, boost::python::detail::not_specified, boost::python::detail::not_specified>::register_aux' requested here
        class_metadata::register_aux((T*)0);
                        ^
/usr/local/include/boost/python/class.hpp:497:19: note: in instantiation of member function 'boost::python::objects::class_metadata<cic<double>, boost::python::detail::not_specified, boost::python::detail::not_specified, boost::python::detail::not_specified>::register_' requested here
        metadata::register_(); // set up runtime metadata/conversions
                  ^
/usr/local/include/boost/python/class.hpp:209:15: note: in instantiation of function template specialization 'boost::python::class_<cic<double>, boost::python::detail::not_specified, boost::python::detail::not_specified, boost::python::detail::not_specified>::initialize<boost::python::init_base<boost::python::init<int, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_> > >' requested here
        this->initialize(i);
              ^
/Users/user/GitHubStuff/boost_cic_test/py_cic_double.cpp:24:2: note: in instantiation of function template specialization 'boost::python::class_<cic<double>, boost::python::detail::not_specified, boost::python::detail::not_specified, boost::python::detail::not_specified>::class_<boost::python::init<int, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_, mpl_::void_> >' requested here
        class_< cic<double> >("cic_double", init< int >())
        ^
/Users/user/GitHubStuff/boost_cic_test/py_cic_double.cpp:11:32: note: candidate constructor (the implicit copy constructor) not viable: 1st argument ('typename reference_wrapper<const cic<double> >::type' (aka 'const cic<double>')) would lose const qualifier
template <class Numeric> class cic {
                               ^
/Users/user/GitHubStuff/boost_cic_test/py_cic_double.cpp:14:2: note: candidate constructor not viable: no known conversion from 'typename reference_wrapper<const cic<double> >::type' (aka 'const cic<double>') to 'int' for 1st argument
        cic(int s) :  nacc(3) {
        ^
1 error generated.
make[3]: *** [CMakeFiles/cic_double.dir/py_cic_double.cpp.o] Error 1
make[2]: *** [CMakeFiles/cic_double.dir/all] Error 2
make[1]: *** [all] Error 2
make: *** [all] Error 2

遗憾的是,目前还无法曝光std::unique_ptr使用 boost::python,因为它需要移动语义,而 boost::python 尚不支持这些(更多详细信息here https://stackoverflow.com/questions/20581679/boost-python-how-to-expose-stdunique-ptr)。此外,您不应该从智能指针派生,因为它是这不是一个好的做法 https://stackoverflow.com/questions/3801648/why-doesnt-shared-ptr-have-a-virtual-descructor-and-how-can-i-get-around-this并且它们没有虚拟析构函数(除了许多其他原因)

话虽如此,您还有很多其他选择,其中一些是:

  • use std::auto_ptr作为数据成员,这得到了很好的支持boost::python(假设您的课程不可复制)。然而,一个auto_ptr无法容纳数组(它不会调用正确的变体delete()).
  • use boost::shared_ptr作为数据成员,并在 API 中隐藏其使用。但是,请注意boost::shared_ptr 不能不保存数组数据 https://stackoverflow.com/questions/13061979/shared-ptr-to-an-array-should-it-be-used出于与上述相同的原因。
  • wrap an std::vector<boost::shared_ptr<>>,这将与boost::shared_ptr开箱即用矢量索引套件 http://www.boost.org/doc/libs/1_42_0/libs/python/doc/v2/indexing.html.
  • ...以及许多其他人。

然而,还有很多其他方法,我个人建议重新设计代码,以使用 boost::python 示例中一些更普遍接受的编码和 python 包装实践。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 unique_ptr 与 boost python 结合使用 - boost::shared_ptr 有效,但 unique_ptr 无效 的相关文章

  • pyspark 将 twitter json 流式传输到 DF

    我正在从事集成工作spark streaming with twitter using pythonAPI 我看到的大多数示例或代码片段和博客是他们从Twitter JSON文件进行最终处理 但根据我的用例 我需要所有字段twitter J
  • Numpy - 根据表示一维的坐标向量的条件替换数组中的值

    我有一个data多维数组 最后一个是距离 另一方面 我有距离向量r 例如 Data np ones 20 30 100 r np linspace 10 50 100 最后 我还有一个临界距离值列表 称为r0 使得 r0 shape Dat
  • Cython 和类的构造函数

    我对 Cython 使用默认构造函数有疑问 我的 C 类 Node 如下 Node h class Node public Node std cerr lt lt calling no arg constructor lt lt std e
  • Web API - 访问 DbContext 类中的 HttpContext

    在我的 C Web API 应用程序中 我添加了CreatedDate and CreatedBy所有表中的列 现在 每当在任何表中添加新记录时 我想填充这些列 为此目的我已经覆盖SaveChanges and SaveChangesAsy
  • 如何将图像路径保存到Live Tile的WP8本地文件夹

    我正在更新我的 Windows Phone 应用程序以使用新的 WP8 文件存储 API 本地文件夹 而不是 WP7 API 隔离存储文件 旧的工作方法 这是我如何成功地将图像保存到 共享 ShellContent文件夹使用隔离存储文件方法
  • 如何使用原始 SQL 查询实现搜索功能

    我正在创建一个由 CS50 的网络系列指导的应用程序 这要求我仅使用原始 SQL 查询而不是 ORM 我正在尝试创建一个搜索功能 用户可以在其中查找存储在数据库中的书籍列表 我希望他们能够查询 书籍 表中的 ISBN 标题 作者列 目前 它
  • Github Action 在运行可执行文件时卡住

    我正在尝试设置运行google tests on a C repository using Github Actions正在运行的Windows Latest 构建过程完成 但是当运行测试时 它被卡住并且不执行从生成的可执行文件Visual
  • Qt表格小部件,删除行的按钮

    我有一个 QTableWidget 对于所有行 我将一列的 setCellWidget 设置为按钮 我想将此按钮连接到删除该行的函数 我尝试了这段代码 它不起作用 因为如果我只是单击按钮 我不会将当前行设置为按钮的行 ui gt table
  • Python ImportError:无法导入名称 __init__.py

    我收到此错误 ImportError cannot import name life table from cdc life tables C Users tony OneDrive Documents Retirement retirem
  • 将 xml 反序列化为类,list<> 出现问题

    我有以下 XML
  • 在 Dynamics CRM 插件中访问电子邮件发件人地址

    我正在编写一个 Dynamics CRM 2011 插件 该插件挂钩到电子邮件实体的更新后事件 阶段 40 pipeline http msdn microsoft com en us library gg327941 aspx 并且在此阶
  • Pandas 每周计算重复值

    我有一个Dataframe包含按周分组的日期和 ID df date id 2022 02 07 1 3 5 4 2022 02 14 2 1 3 2022 02 21 9 10 1 2022 05 16 我想计算每周有多少 id 与上周重
  • 为什么 C# Math.Ceiling 向下舍入?

    我今天过得很艰难 但有些事情不太对劲 在我的 C 代码中 我有这样的内容 Math Ceiling decimal this TotalRecordCount this PageSize Where int TotalRecordCount
  • Process.Start 阻塞

    我正在调用 Process Start 但它会阻止当前线程 pInfo new ProcessStartInfo C Windows notepad exe Start process mProcess new Process mProce
  • mysql-connector-c++ - “get_driver_instance”不是“sql::mysql”的成员

    我是 C 的初学者 我认为学习的唯一方法就是接触一些代码 我正在尝试构建一个连接到 mysql 数据库的程序 我在 Linux 上使用 g 没有想法 我运行 make 这是我的错误 hello cpp 38 error get driver
  • 如何使用 std::string 将所有出现的一个字符替换为两个字符?

    有没有一种简单的方法来替换所有出现的 in a std string with 转义 a 中的所有斜杠std string 完成此操作的最简单方法可能是boost字符串算法库 http www boost org doc libs 1 46
  • C 中的异或运算符

    在进行按位操作时 我在确定何时使用 XOR 运算符时遇到一些困难 按位与和或非常简单 当您想要屏蔽位时 请使用按位 AND 常见用例是 IP 寻址和子网掩码 当您想要打开位时 请使用包含或 然而 XOR 总是让我明白 我觉得如果在面试中被问
  • 限制C#中的并行线程数

    我正在编写一个 C 程序来生成并通过 FTP 上传 50 万个文件 我想并行处理4个文件 因为机器有4个核心 文件生成需要更长的时间 是否可以将以下 Powershell 示例转换为 C 或者是否有更好的框架 例如 C 中的 Actor 框
  • 使用 z = f(x, y) 形式的 B 样条方法来拟合 z = f(x)

    作为一个潜在的解决方案这个问题 https stackoverflow com questions 76476327 how to avoid creating many binary switching variables in gekk
  • 使用 libcurl 检查 SFTP 站点上是否存在文件

    我使用 C 和 libcurl 进行 SFTP FTPS 传输 在上传文件之前 我需要检查文件是否存在而不实际下载它 如果该文件不存在 我会遇到以下问题 set up curlhandle for the public private ke

随机推荐