【发布时间】:2016-09-04 00:45:38
【问题描述】:
我正在用 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++ 函数外,我不需要操作查找表。
【问题讨论】:
-
如果变量
really_big_array是在全局范围内声明的,那么声明正确的所有 translation units*都可以访问它。 -
use_one_way不采用self参数。这是您告诉我们that isn't my actual code的地方,我们想知道您到底希望我们根据什么来回答。 -
@kfsone 差不多了,我在这里告诉你
that isn't my actual code but my actual code shared the same problem,我实际上是个白痴。可能是因为试图让 boost 像我之前想要的那样工作,以至于当其他事情发生时,我被卡住了,认为这是罪魁祸首。感谢您在我没有发现的时候发现了明显的问题。感谢 Joachim 至少让我担心我刚刚做了一些愚蠢的事情。
标签: python c++ boost-python