2009-06-02 44 views
4

我是C++/Python混合語言編程的新手,對Python/C API沒有太多的想法。我剛開始使用Boost.Python來封裝Python的C++庫。我被困在包裝一個函數,該函數將指針指向一個數組作爲參數。 (2nd ctor)是C++中的原型。如何將指針傳遞給Python中的數組以用於包裝C++函數

class AAF{ 
    AAF(AAF_TYPE t); 
    AAF(double v0, const double * t1, const unsigned * t2, unsigned T); 
    ~AAF(); 
} 

我是否正確地把它包裝在boost :: python中?

class_<AAF>("AAF", init<AAF_TYPE>()) 
    .def(init<double, const double*, const unsigned*, unsigned>()); 

請注意,它編譯和鏈接成功,但我無法弄清楚如何在Python中調用它。我天真的嘗試像下面的失敗。

>>> z = AAF(10, [4, 5.5, 10], [1, 1, 2], 3); 

Traceback (most recent call last): 
    File "./test_interval.py", line 40, in <module> 
    z = AAF(10, [4, 5.5, 10], [1, 1, 2], 3); 
Boost.Python.ArgumentError: Python argument types in 
    AAF.__init__(AAF, int, list, list, int) 
did not match C++ signature: 
    __init__(_object*, AAF_TYPE) 
    __init__(_object*, double, double const*, unsigned int const*, unsigned int) 

>>> t1 = array.array('d', [4, 5.5, 10]) 
>>> t2 = array.array('I', [1, 1, 2]) 
>>> z = AAF(10, t1, t2, 3); 

Traceback (most recent call last): 
    File "./test_interval.py", line 40, in <module> 
    z = AAF(10, t1, t2, 3); 
Boost.Python.ArgumentError: Python argument types in 
    AAF.__init__(AAF, int, array.array, array.array, int) 
did not match C++ signature: 
    __init__(_object*, AAF_TYPE) 
    __init__(_object*, double, double const*, unsigned int const*, unsigned int) 

我的第二個問題是,我是否也需要包裝析構函數?請說明在某些情況下這可能是必要的,但並非總是如此。

回答

4

的包裝是正確的(原則),但在

AAF(10, [4, 5.5, 10], [1, 1, 2], 3); 

(如解釋指出),你傳遞給你的函數python的列表對象,不是指針。

簡而言之,如果你的函數只需要在python的列表上工作,你需要改變你的代碼來使用那個接口(而不是使用指針)。如果你需要保持這個接口,你必須編寫一個包裝函數,它接受來自python的列表,做適當的轉換並調用你的原始C++函數。這同樣適用於numpy數組。

請注意,boost :: python提供了一些內置機制來將python容器轉換爲stl兼容容器。

您的情況的一個例子包裝代碼可能是

void f(list o) { 
    std::size_t n = len(o); 
    double* tmp = new double[n]; 
    for (int i = 0; i < n; i++) { 
     tmp[i] = extract<double>(o[i]); 
    } 
    std::cout << std::endl; 
    // use tmp 
    delete tmp; 
} 

請給看看Boost.Python的教程在http://www.boost.org/doc/libs/1_39_0/libs/python/doc/tutorial/doc/html/index.html

+0

感謝您的回覆,但正如我所說的,我對Python/C API沒有太多的想法。你能指點什麼地方,以便我可以找到一種方法將Python列表轉換爲C++數組嗎? – Aamir 2009-06-02 18:40:20