使用SWIG for Python转换Linux中的字符串

时间:2015-05-05 14:05:18

标签: python c++ linux swig

我有一个能够以普通ASCII或宽格式输出字符串的C ++类。我想将Python中的输出作为字符串。我正在使用SWIG(版本3.0.4)并阅读了SWIG文档。我正在使用以下typemap从标准c字符串转换为我的C ++类:

%typemap(out) myNamespace::MyString &
{
    $result = PyString_FromString(const char *v);
}

这在使用VS2010编译器的Windows中运行良好,但它在Linux中无法正常运行。当我在Linux下编译包装文件时,我收到以下错误:

error: cannot convert ‘std::string*’ to ‘myNamespace::MyString*’ in assignment

所以我尝试将额外的typemap添加到Linux接口文件中,如下所示:

%typemap(in) myNamespace::MyString*
{
    $result = PyString_FromString(std::string*);
}

但我仍然得到同样的错误。如果我手动进入包装代码并按如下方式修改分配:

arg2 = (myNamespace::MyString*) ptr;

然后代码编译得很好。我不明白为什么我的附加类型图不起作用。任何想法或解决方案将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:1)

看起来你的typemap非常正确地使用了这些参数。你应该有这样的东西:

%typemap(out) myNamespace::MyString &
{
    $result = PyString_FromString($1);
}

'$ 1'是第一个参数。有关详细信息,请参阅SWIG special variables [http://www.swig.org/Doc3.0/Typemaps.html#Typemaps_special_variables]

修改

要处理输入类型图,您需要这样的内容:

%typemap(in) myNamespace::MyString*
{
    const char* pChars = "";
    if(PyString_Check($input))
    {
        pChars = PyString_AsString($input);
    }
    $1 = new myNamespace::MyString(pChars);
}

您可以使用以下代码执行更多错误检查和处理Unicode:

%typemap(in) myNamespace::MyString*
{
    const char* pChars = "";
    PyObject* pyobj = $input;
    if(PyString_Check(pyobj))
    {
        pChars = PyString_AsString(pyobj);
        $1 = new myNamespace::MyString(pChars);
    }
    else if(PyUnicode_Check(pyobj))
    {
        PyObject* tmp = PyUnicode_AsUTF8String(pyobj);
        pChars = PyString_AsString(tmp);
        $1 = new myNamespace::MyString(pChars);
    }
    else
    {
        std::string strTemp;
        int rrr = SWIG_ConvertPtr(pyobj, (void **) &strTemp, $descriptor(String), 0);
        if(!SWIG_IsOK(rrr))
            SWIG_exception_fail(SWIG_ArgError(rrr), "Expected a String "
        "in method '$symname', argument $argnum of type '$type'");
        $1 = new myNamespace::MyString(strTemp);
    }
}