9

プログラムを高速化するために、次の python 関数を置き換える C++ 拡張機能を作成しようとしています。

Python関数は次のようになります

def calc_dist(fea1, fea2):
    #fea1 and fea2 are two lists with same length
    ...

次のように、c ++とboost pythonを使用して関数を作成しました。

#include <vector>
#include <boost/python.hpp>
double calc_dist(vector<double>& fea1, vector<double>& fea2)
{
    int len = fea1.size();
    double s=0;
    for(int i=0; i<len;i++){
        double p=fea1[i];
        double q=fea2[i];
        ...//calculating..
    }
    return s;
}
BOOST_PYTHON_MODULE(calc_dist)
{
    using namespace boost::python;
    def("calc_dist",calc_dist);
}

上記のcppコードを次のような.soファイルにコンパイルします

g++ calc_dist.cpp -shared -fPIC -o calc_dist.so -I /usr/include/python2.6 -lboost_python

Pythonプログラムで.soを使用しようとすると、インポートは正常に機能し、モジュールが正常にインポートできることを示します。

ただし、関数のパラメーターに2つのリストを渡すたびに、pythonは次のようなエラーを返します

ArgumentError: Python argument types in
    calc_dist.calc_dist(list, list)
did not match C++ signature:
    calc_dist.calc_dist(std::vector<float, std::allocator<float> >,
                        std::vector<float, std::allocator<float> >)

誰でもこの問題を解決する方法を教えてもらえますか? つまり、boost を使用して Python リストを C++ 拡張機能に渡しますか?

どうもありがとう!

4

1 に答える 1

11

std::vectorPython リストで操作したい場合に受け入れる関数を作成したのはなぜですか? それらは別のものです。

Boost.Python は、Python リストをリストクラスとして公開します。

したがって、関数は次のようになります

double calc_dist(boost::python::list fea1, boost::python::list fea2)
{
    boost::python::ssize_t len = boost::python::len(fea1);
    double s=0;
    for(int i=0; i<len;i++){
        double p = boost::python::extract<double>(fea1[i]);
        double q = boost::python::extract<double>(fea2[i]);
        ...//calculating..
    }
    return s;
}

それはテストされていませんが、うまくいけば、あなたが始めるのに十分近いです...

于 2012-05-18T11:58:32.367 に答える