Boost-无法在vriables中包装传递

Boost - Cannot wrap pass-in vriables

本文关键字:包装 vriables Boost-      更新时间:2023-10-16

我试图使用<boost/python>将列表包装为字符串向量,其中出现"未定义符号"错误:

/* *.cpp */
using namespace std;
using namespace boost::python;
// convert python list to vector
vector<string> list_to_vec_string(list& l) {
    vector<string> vec;
    for (int i = 0; i < len(l); ++i)
        vec.push_back(extract<string>( l[i] ));
    return vec;
};
bool validateKeywords(list& l){
    vector<string> keywords = list_to_vec_string(l);
    // do somethoing
};

我有

/* wrapper.cpp */
BOOST_PYTHON_MODULE(testmodule){
    // expose just one function
    def("validateKeywords", validateKeywords);
}

导入模块时,返回错误。

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: /usr/local/lib/python2.7/dist-packages/testmodule.so: undefined symbol: _Z16validateKeywordsSt6vectorISsSaISsEE

在我的测试中,如果我只转换返回的值,即从vector<string>list,一切都很好。只是无法使其与传入变量一起工作。除非传入不需要包装器的类型(int、char、bool、void),否则问题不会消失。


更新

你能做什么:

/*pass in a variable that do not need a wrapper*/
// testmodule.cpp
void sayHello(const std::string& msg) {
    std::cout << msg << endl;
}
// wrapper.cpp
BOOST_PYTHON_MODULE(testmodule) {
    def("sayHello", sayHello);
}
// demo.py
import testmodule as tm
tm.sayHello('hello!')
// output
>> hello!
/*wrap a returned value from a function*/
// testmodule.cpp
vector<int> vecint(int i) {
    vector<int> v(i);
    return v;
}
// wrapper.cpp
boost::python::list vecint_wrapper(int i) {
    boost::python::list l;
    vector<int> v = vecint(i);
    for (int j=0; j<v.size(); ++j)
        l.append(v[j]);
    return l; // then you have a list
}
/*cannot change passed in values to more complicate types*/

您错过了在行中获取参考

def("validateKeywords", validateKeywords);

尝试使用

def("validateKeywords", &validateKeywords );

我得到了。您不能在C++实现中定义包装器,但可以在包装器层中定义。虽然我不知道为什么,但你可以:

/* wrapper.cpp */
bool validateKeys(list l) {
    vector<string> keys;
    // so you can accept a python list!
    for (int i; i < len(l); ++i) keys.push_back(extract<string>(l[i]));
    return validateKeywords(keys);
}
// module
BOOST_PYTHON_MODULE(testmodule){
    def("validateKeys", validateKeys); // use wrapped function, just that simple
}