使用SWIG for Python在Linux中转换字符串 我有一个C++类,能够输出普通ASCII或宽格式的字符串。我想以字符串的形式获得Python中的输出。我正在使用SWIG(3.0.4版),并且已经阅读了SWIG文档。我使用下面的类型映射把一个标准的C字符串转换成我的C++类: %typemap(out) myNamespace::MyString & { $result = PyString_FromString(const char *v); }
这在使用VS2010编译器的Windows中运行良好,但在Linux中无法完全运行。在Linux下编译wrap文件时,出现以下错误:使用SWIG for Python在Linux中转换字符串 我有一个C++类,能够输出普通ASCII或宽格式的字符串。我想以字符串的形式获得Python中的输出。我正在使用SWIG(3.0.4版),并且已经阅读了SWIG文档。我使用下面的类型映射把一个标准的C字符串转换成我的C++类: %typemap(out) myNamespace::MyString & { $result = PyString_FromString(const char *v); },python,c++,linux,swig,Python,C++,Linux,Swig,这在使用VS2010编译器的Windows中运行良好,但在Linux中无法完全运行。在Linux下编译wrap文件时,出现以下错误: error: cannot convert ‘std::string*’ to ‘myNamespace::MyString*’ in assignment 因此,我尝试向Linux接口文件添加一个额外的typemap,如下所示: %typemap(in) myNamespace::MyString* { $result = PyString_FromS
error: cannot convert ‘std::string*’ to ‘myNamespace::MyString*’ in assignment
因此,我尝试向Linux接口文件添加一个额外的typemap,如下所示:
%typemap(in) myNamespace::MyString*
{
$result = PyString_FromString(std::string*);
}
但我还是犯了同样的错误。如果我手动进入包装代码并按如下方式修复分配:
arg2 = (myNamespace::MyString*) ptr;
然后代码就可以编译了。我不明白为什么我的附加类型映射不起作用。任何想法或解决方案都将不胜感激。提前感谢。您的类型映射似乎没有完全正确地使用参数。你应该有这样的东西:
%typemap(out) myNamespace::MyString &
{
$result = PyString_FromString($1);
}
其中,“$1”是第一个参数。有关更多信息,请参阅[
编辑:
要处理输入类型映射,您需要如下内容:
%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);
}
}
@Devian-非常感谢您的代码示例,它在我的32位和64位构建中运行良好。另外两种构建类型是32位和64位宽字符构建。对于宽字符构建,我需要在我的SWIG接口文件中同时包含std_wiostream.I和std_wstream.I文件。当我包含这些文件时,我会得到无关的SWIG状态nts包含在包装文件中。这些语句的形式为:if(SWIG_IsNewObj(res2))delete arg2;这些语句会导致编译器错误,因为变量res2不存在。知道为什么要在包装文件中插入这些行吗?