![](/img/trans.png)
[英]How to wrap a c++ function which takes in a function pointer in python using SWIG
[英]How can you wrap a C++ function with SWIG that takes in a Python numpy array as input without explicitly giving a size?
我有一個 C++ 類庫,我正在構建一個使用 SWIG 的 Python 接口。 這些類中的許多類具有在不輸入大小的情況下接受 double* 數組或 int* 數組參數的方法。 例如,有許多方法具有如下聲明之一:
void func(double* array);
void func2(double* array, double unrelated_parameter, ...);
我希望能夠在 Python 中使用這些函數,用戶傳入一個 Python numpy 數組。 這些數組的大小永遠不會作為函數的參數給出。 輸入數組的大小在這些 C++ 類的對象的構造函數中給出,並且假設作為這些類方法的參數給出的每個輸入數組都具有相同的大小。 我見過的所有 numpy 示例都要求我將一個 int array_size 參數添加到被包裝的 C++ 方法/函數中。
有沒有一種方法可以包裝這些 C++ 函數,而無需更改我的整個 C++ 庫的 API 以包含每個函數的 int array_size 參數? 理想情況下,用戶應該傳入一個 Python numpy 數組,SWIG 會在 C++ 端自動將其轉換為 double 或 int 數組。
我已經包含了 numpy.i 並按照此處的說明進行操作:https ://numpy.org/doc/stable/reference/swig.interface-file.html 但出現如下錯誤:
TypeError:在方法'func'中,'double *'類型的參數2
我能想到的一種方法是抑制函數的“無大小”版本並將類擴展為具有使用類中的實際參數的一次性維度變量的版本。
例子:
測試.i
%module test
%{
#define SWIG_FILE_WITH_INIT
class Test {
public:
int _dim; // needs to be public, or have a public accessor.
Test(int dim) : _dim(dim) {}
double func(double* array) {
double sum = 0.0;
for(int i = 0; i < _dim; ++i)
sum += array[i];
return sum;
}
};
%}
%include "numpy.i"
%init %{
import_array();
%}
%apply (double* IN_ARRAY1, int DIM1) {(double* array, int /*unused*/)};
%ignore Test::func; // so the one-parameter version isn't wrapped
class Test {
public:
Test(int dim);
double func(double* array);
};
%rename("%s") Test::func; // unignore so the two-parameter version will be used.
%extend Test {
double func(double* array, int /*unused*/) {
return $self->func(array);
}
}
演示:
>>> import test
>>> t = test.Test(5)
>>> import numpy as np
>>> a = np.array([1.5,2.0,2.5,3.75,4.25])
>>> t.func(a)
14.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.