使用SWIG类型映射通过字符串转换类型

时间:2014-09-08 20:29:02

标签: python c++ ruby type-conversion swig

我正在使用swig为某些类生成包装器。一个类获取QUuid(std :: list)列表(见下文)。有一个toString,它给出了一个std :: string,而python也可以通过使用这个字符串来实例化它的uuid。我如何生成一个类型图(或者可能是其他可能更好的东西),它使用上面描述的转换为python,反之亦然。如果它也独立于目标语言,那将是最好的(至少我还需要ruby包装器)。

由于

IRPICurrentPositionsCommand.h:

class IRPICurrentPositionsCommand : public CommandBase
{
  Q_OBJECT

  COMMAND_IMPLEMENTATION_BASICS(IRPICurrentPositionsCommand, ir)

public:
  std::list<QUuid> GetAxisIDs() const
  {
    return m_AxisIDs;
  }

  void SetAxisIDs(std::list<QUuid> arg)
  {
    m_AxisIDs = arg;
  }

  std::list<double> GetAxisPostions() const
  {
    return m_AxisPostions;
  }

  void SetAxisPostions(std::list<double> arg)
  {
    m_AxisPostions = arg;
  }

private:
  std::list<QUuid> m_AxisIDs;
  std::list<double> m_AxisPostions;

protected:

  /** @see ora::CommandBase::Serialize(QDataStream &stream) **/
  virtual void Serialize(QDataStream &stream) const;

  /** @see ora::CommandBase::Deserialize(QDataStream &stream) **/
  virtual void Deserialize(QDataStream &stream);
};

1 个答案:

答案 0 :(得分:0)

这是std::list<QUuid>个对象的SWIG / Python模板。我不熟悉Ruby,但希望这会给你一些关于打字的见解。

// To use std::string
%include "std_string.i"

%typemap(out) std::list<QUuid>
{
    PyObject* outList = PyList_New(0);

    int error;

    std::list<QUuid>::iterator it;
    for ( it=$1.begin() ; it != $1.end(); it++ )
    {
        PyObject* pyQUuid = SWIG_NewPointerObj(new QUuid(*it), SWIGTYPE_p_QUuid, SWIG_POINTER_OWN );

        error = PyList_Append(outList, pyQUuid);
        Py_DECREF(pyQUuid);
        if (error) SWIG_fail;       
    }

    $result = outList;
}

%typemap(in) std::list<QUuid>
{
    //$input is the PyObject
    //$1 is the parameter

    if (PyList_Check($input))
    {
        std::list<QUuid> listTemp;

        for(int i = 0; i<PyList_Size($input); i++)
        {
            PyObject* pyListItem = PyList_GetItem($input, i);

            QUuid* arg2 = (QUuid *) 0 ;

            int res1 = 0;
            void *argp1;

            res1 = SWIG_ConvertPtr(pyListItem, &argp1, SWIGTYPE_p_QUuid,  0  | 0);
            if (!SWIG_IsOK(res1))
            {
                PyErr_SetString(PyExc_TypeError,"List must only contain QUuid objects");
                return NULL;
            }  
            if (!argp1)
            {
                PyErr_SetString(PyExc_TypeError,"Invalid null reference for object QUuid");
                return NULL;
            }

            arg2 = reinterpret_cast< QUuid * >(argp1);
            listTemp.push_back(*arg2);
        }

        $1 = listTemp;
    }
    else
    {
        PyErr_SetString(PyExc_TypeError,"Wrong argument type, list expected");
        return NULL;
    }
}