简体   繁体   English

如何使用 SWIG 在 C++ 中调用 python 函数?

[英]How do I call a python function in C++ using SWIG?

I have a the following C++我有以下 C++

class myfun{
public:
    virtual double eval(arma::vec& x){};
};

double op(myfun* f, arma::vec& x){
    return f->eval(x);
}

where arma::vec is an armadillo c++ vector for which I am using armanpy.i to translate a numpy array as an arma::vec object and vice versa.其中arma::vec是 armadillo c++ 向量,我使用 armanpy.i 将 numpy 数组转换为 arma::vec 对象,反之亦然。

After enabling the swig directors, and creating a SWIG interface for the above C++ code, I create a python class which redefine's the eval virtual method:在启用 swig 控制器并为上述 C++ 代码创建一个 SWIG 接口后,我创建了一个重新定义了 eval 虚拟方法的 python 类:

class f(mymodule.myfun):
    def __init__(self):
        super(f,self).__init__()
    def eval(self,x):
        print x
        return 3.14

In python, I first create an instance of f, which inherits myfun:在python中,我首先创建了一个f的实例,它继承了myfun:

b = f()

Then, I pass this to op :然后,我将其传递给op

mymodule.op(b,array([3.,4.]))

which outputs哪个输出

<Swig Object of type 'arma::vec *' at 0x10e6dcc30>
3.14

Python is not interpreting arma::vec * as a numpy array, which I thought it was doing in the armanpy.i file. Python 没有将 arma::vec * 解释为一个 numpy 数组,我认为它是在 armanpy.i 文件中执行的。 Any ideas?有任何想法吗? I am not married to arma::vec and I could replace arma::vec with a numpy vector.我没有和 arma::vec 结婚,我可以用一个 numpy 向量替换 arma::vec。

Thanks!谢谢!

在您的情况下,请查看提供 armadillo SWIG 文件的armanpy

You can accomplish this using this repository at Github which makes use of armanpy and armadillo 8.500.1您可以使用 Github 上的此存储库完成此操作,该存储库使用了 armanpy 和 armadillo 8.500.1

https://github.com/Wolframm74/armadillo_armanpy/blob/master/README.md https://github.com/Wolframm74/armadillo_armanpy/blob/master/README.md

Start with compiling the code by following the steps and then building upon the examples.从按照步骤编译代码开始,然后在示例的基础上进行构建。 It has examples with how to translate python's numpy arrays into armadillo arrays via SWIG.它有关于如何通过 SWIG 将 python 的 numpy 数组转换为犰狳数组的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM