簡體   English   中英

如何在Python中為包裝的C ++函數傳遞指向數組的指針

[英]How to pass pointer to an array in Python for a wrapped C++ function

我是C ++ / Python混合語言編程的新手,對Python / C API並不太了解。 我剛開始使用Boost.Python來包裝Python的C ++庫。 我被困在包裝一個函數,該函數將指向數組的指針作為參數。 以下(第二個ctor)是它在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)

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

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

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;
}

請查看http://www.boost.org/doc/libs/1_39_0/libs/python/doc/tutorial/doc/html/index.html上的boost.python教程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM