通过boost python从python中提取常量值

Extract constant value from python by boost python

本文关键字:python 常量 提取 boost 通过      更新时间:2023-10-16

python代码

import ldap,ldif
l = ldap.initialize('ldaps://RIO-PC:636')
l.set_option(ldap.OPT_TIMEOUT);

我想提取ldap的常数值。OPT_TIMEOUT,但是如何呢?

#include <iostream>
#include <boost/python.hpp>
int main()
{
    namespace bp = boost::python;
    try{
        Py_Initialize();
        bp::object main_module = bp::import("__main__");
        bp::import("ldap");
        bp::import("ldif");
        bp::object main_namespace = main_module.attr("__dict__");
        bp::exec("import ldap,ldifn"
                 "l = ldap.initialize('ldaps://RIO-PC')n",
             main_namespace);
        boost::python::object ldap = boost::python::extract<boost::python::object>(main_namespace["l"]);
        ldap.attr("OPT_TIMEOUT"); //this line will throw exception
    }catch(boost::python::error_already_set const &){               
        PyErr_Print();
        PyErr_Clear();
    }
}

错误信息是

AttributeError: SimpleLDAPObject没有属性'OPT_TIMEOUT'

环境

编译器:vc2008Boost版本:1.55_0操作系统:win7 64bits(x64)

您的c++代码试图提取l.OPT_TIMEOUT,而不是ldap.OPT_TIMEOUT。试着

    bp::object ldap_module = bp::import("ldap");
    ldap_module.attr("OPT_TIMEOUT");