1

我正在尝试用 boost::python 包装一个 C++ 单例:

class EigenSolver {
    private:
        static EigenSolver* _self;
        static int _refCount;
    protected:
        EigenSolver();
        ~EigenSolver();

    private:
        EigenSolverOptions _options;
        BasicTypes::Array<double> eigenValues;
        BasicTypes::RegularArray <double> eigenVectors;

    public:
        // singleton initialization, returns unique instance
        static EigenSolver* Instance() {
            if (!_self) _self = new EigenSolver();
            return _self;
        }
        // singleton memory free
        void FreeInst() {
            _refCount--;
            if (!_refCount) {
                delete this;
                _self = NULL;
            }
        }
};

包装代码:

py::class_<EigenSolver, boost::shared_ptr<EigenSolver>, boost::noncopyable>
    ("EigenSolver", py::no_init)
    .def("Instance", &EigenSolver::Instance, py::return_internal_reference<>())

当我尝试编译库时,出现未解决的外部符号错误:

error LNK2001: unresolved external symbol 
"private: static class UTILS::EigenSolver * UTILS::EigenSolver::_self" 
(?_self@EigenSolver@UTILS@@0PEAV12@EA)
PythonBindingsSolverLib.lib
What is the right way to wrap a C++ singleton class?

使用 boost::python 包装 C++ 单例类的正确方法是什么?

在此先感谢,伊万。

4

1 回答 1

0

使用C++ Singleton 设计模式问题中提供的实现解决了该问题:

py::class_<EigenSolver, boost::shared_ptr<EigenSolver>, boost::noncopyable>
    ("EigenSolver", py::no_init)
    .add_property("instance", py::make_function(&EigenSolver::Instance, 
    py::return_value_policy<py::reference_existing_object>()))
;
于 2012-09-20T16:52:27.590 回答