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

Convert types via string using SWIG typemaps

本文关键字:类型 字符串 转换 映射 SWIG 使用      更新时间:2023-10-16

我正在使用swig为某些类生成包装器。一个类采用一个QUuid列表(std::list)(见下文)。有一个toString,它提供一个std::字符串,python也可以使用这个字符串实例化它的uuid。我如何生成一个类型映射(或者其他更好的方法),它使用上面描述的到python的转换,反之亦然。最好是独立于目标语言(至少我也需要ruby包装器)。

感谢

IRPIC当前位置命令.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);
};

这里是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;
    }
}