Python接口的C ++库的%类型映射 [英] %typemapping of a C++ Library for Python Interface

查看:423
本文介绍了Python接口的C ++库的%类型映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的C ++库创建一个python包装器。这将是很酷,如果有一个自动转换std :: vector到python列表,反之亦然。
不幸的是,如果我将这个代码添加到我的接口文件中,我仍然会在运行时遇到错误。

I want to create a python wrapper for my C++ library. It would be cool, if there is a automatic conversion of std::vector to python lists and the other way round. Unfortunatly if I add this code to my Interface-file I still get errors in run-time.

%typemap(in) std::vector<float> value (std::vector<float> vIn) {
    int iLen = PySequence_Length($input); 
    for(unsigned int i = 0; i < iLen; i++) {
        PyObject *o = PySequence_GetItem($input, i);
        if (PyNumber_Check(o)) {
            vIn.push_back((float)PyFloat_AsDouble(o) );
        }
    }
    $1 = vIn;
}
%typemap(out) std::vector<float> {
    std::vector<float> vOut = $1;
    int iLen = vOut.size();
    $result = PyList_New(iLen);
    for(unsigned int i = 0; i < iLen; i++) {
        double fVal = vOut.at(i);
        PyObject *o = PyFloat_FromDouble((double) fVal);
        PyList_SetItem($result, i, o);
    }
}

类标题:

class TrainingSet {
    private:
        std::vector<std::vector<float> > m_vInputList;
        std::vector<std::vector<float> > m_vOutputList;
    public:
        void AddInput(const std::vector<float> &vIn);
    // ..

Python代码:

trainSet = TrainingSet()
trainSet.AddInput([0.5, 0.5, 0.5])

错误:

File "runSOMNet.py", line 9, in <module>
trainSet.AddInput([0.5, 0.5, 0.5])
File "/home/dgrat/annetgpgpu/build/ANNet/ANPyNetCPU.py", line 674, in AddInput
def AddInput(self, *args): return _ANPyNetCPU.TrainingSet_AddInput(self, *args)
NotImplementedError: Wrong number or type of arguments for overloaded function      'TrainingSet_AddInput'.
Possible C/C++ prototypes are:
ANN::TrainingSet::AddInput(std::vector< float,std::allocator< float > > const &)
ANN::TrainingSet::AddInput(float *,unsigned int const &)


推荐答案

如果你要手动定义%typemap ,你还需要一个%typemap(check),例如:

If you're going to define the %typemaps manually, you will also need a %typemap(check), something like:

%typemap(typecheck) std::vector<float>& {
    $1 = PySequence_Check($input) ? 1 : 0;
}

我相信经验法则是,如果你定义一个%typemap(in),你还应该定义一个%typemap(check) ---否则,生成的代码永远不会到达where它会把你的%typemap(in)

I believe the rule of thumb is that if you define a %typemap(in), you should also define a %typemap(check) --- otherwise, the generated code never gets to where it's put your %typemap(in).

这篇关于Python接口的C ++库的%类型映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆