使用boost::python从c++函数访问大型表

Large table access from c++ functions with boost::python

本文关键字:访问 大型 函数 boost python 使用 c++      更新时间:2023-10-16

我正在c++中生成一个非常大的查找表,并在各种c++函数中使用它。使用boost::python将这些函数暴露给python。

当不作为类的一部分使用时,实现了期望的行为。当我尝试使用函数作为仅用python编写的类的一部分时,我遇到了访问查找表的问题。

    ------------------------------------
    C++ for some numerical heavy lifting
    ------------------------------------
    include <boost/python>
    short really_big_array[133784630]
    void fill_the_array(){
      //Do some things which populate the array
    }
    int use_the_array(std::string thing){
      //Lookup a few million things in the array depending on thing
      //Return some int dependent on the values found
    }
    BOOST_PYTHON_MODULE(bigarray){
      def("use_the_array", use_the_array)
      def("fill_the_array", fill_the_array)
    }
    ---------
    PYTHON Working as desired
    ---------
    import bigarray
    if __name__ == "__main__"
        bigarray.fill_the_array()
        bigarray.use_the_array("Some Way")
        bigarray.use_the_array("Some Other way")
    #All works fine
    ---------
    PYTHON Not working as desired
    ---------
    import bigarray
    class BigArrayThingDoer():
    """Class to do stuff which uses the big array,
    use_the_array() in a few different ways
    """
    def __init__(self,other_stuff):
        bigarray.fill_the_array()
        self.other_stuff = other_stuff
    def use_one_way(thing):
        return bigarray.use_the_array(thing)
    if __name__ == "__main__"
        big_array_thing_doer = BigArrayThingDoer()
        big_array_thing_doer.use_one_way(thing)
    #Segfaults or random data

我想我可能没有暴露足够的python来确保数组在正确的时间是可访问的,但我不太确定我应该暴露什么。同样有可能存在某种问题,涉及到查找表的所有权。

我不需要操作查找表,除非通过其他c++函数。

定义中缺少self。使用关键字参数,我可能应该使用关键字参数,所以运行时没有错误。