Boost不能包装passin变量

2024-10-03 11:15:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用<boost/python>将列表包装为字符串向量,其中出现了“undefined symbol”错误:

/* *.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*/

Tags: toinstringreturnwrappercpplistint
2条回答

您未在以下行中获得参考:

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
}

相关问题 更多 >