我的代码主要是 C++,但我想使用 SWIG director 选项在 python 中重新定义一个 C++ 虚函数,然后将该函数传回 C++。下面是一个简化的例子。
这是我的 C++ 基类,带有虚函数 fun
。 fun
接受 (double* x, int n)
,它允许我将一个 numpy 数组传递给它。
class base{
public:
virtual double fun(double* x, int n){return 0.0;}
};
我有另一个接受这个基类的类:
class main{
public:
base* b_;
main(base& b){
b_ = &b;
}
};
这个类有一个构造函数,它接收一个基类并存储一个指向它的指针 (b_
)。
我可以成功地将 swig 接口(interface)编译成一个名为 mymodule
的模块,确保启用 director(请参阅下面的 SWIG 接口(interface)文件),并且根据 SWIG director 文档,我继承了基类和重新定义虚函数 fun
如下:
import mymodule
class base(mymodule.base):
def __init__(self):
super(base,self).__init__()
def fun(self,x):
return x[0]
然后我将它传递给 main
类:
b = base()
m = mymodule.main(b)
但是,当我尝试 m.b_.fun(array([1.,2.]))
时,我得到了一个 TypeError
:
TypeError: 'SwigPyObject' object has no attribute '__getitem__'
关于如何让它发挥作用的任何想法?我认为当我将 b
传递到 mymodule.main 时,C++ 将 x
视为双 * 指针并且不知道如何处理它。
顺便说一下,这是我的 swig 接口(interface)文件:
%module(directors="1") mymodule
%{
#define SWIG_FILE_WITH_INIT
/* Includes the header in the wrapper code */
#include "myclasses.h"
%}
%feature("director") base;
%init %{
import_array();
%}
%apply (double* IN_ARRAY1, int DIM1) {(double* x, int n)};
/* Parse the header file to generate wrappers */
%include "myclasses.h"
最佳答案
这看起来像是 Python 的所有权问题。
向 SWIG 提供提示:
%new double *fun(double* IN_ARRAY1, int DIM1) {(double* x, int n)};
还要注意指向函数本身的指针。 当使用 %new 时,Python 模块将分配对象的适当所有权。这就是为什么您可以在调用中使用值而不是变量的原因。
关于python - 使用 SWIG Controller 将 python 中的 numpy 函数传递给 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29268630/