下面是一个非常简单的C函数:
bool GetSomething(string* result)调用此函数后,返回值应指示result是否保存所需信息,用户可以检查返回值以相应处理。
要在Python代码中使用这个函数,我使用默认的typemaps.i文件,然后将函数更改为
bool GetSomething(string* OUTPUT)这是可行的,但仍然很麻烦。我必须这样做才能得到我想要的结果:
success, result = GetSomething()
if success:
# handle result
else:
# throw exception理想情况下,我希望有这个接口,而不是:
result = GetSomething()
if result:
# handle result任何帮助都将不胜感激。
发布于 2014-09-05 03:04:36
下面是注释中提到的想法的一个示例.i文件。将成功的返回状态转换为None,将失败的返回状态转换为异常,并将输出参数附加到返回值中。这不需要更改C++代码库:
%module x
%include <exception.i>
// convert non-zero int return values to exceptions
%typemap(out) int %{
if($1)
SWIG_exception(SWIG_RuntimeError,"non-zero return value");
$result = Py_None;
Py_INCREF(Py_None); // Py_None is a singleton so increment its reference if used.
%}
// Easy way for int*, but customize below for more complicated types
// %apply int* OUTPUT {int*};
// suppress the output parameter as an input.
%typemap(in,numinputs=0) int* (int tmp) %{
$1 = &tmp;
%}
// append int* output parameters to the return value.
%typemap(argout) int* {
PyObject* tmp = PyLong_FromLong(*$1);
$result = SWIG_Python_AppendOutput($result,tmp);
}
// %inline declares and exposes a function
%inline %{
int func(int val, int* pOut)
{
if(val < 1)
return 1;
*pOut = 2 * val;
return 0;
}
%}如果您使用.i并将结果编译为swig -python -c++ x.i扩展名,则可以使用swig -python -c++ x.i:
>>> import x
>>> x.func(2)
4
>>> x.func(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: non-zero return value发布于 2014-09-04 15:43:08
我现在的黑客,希望这能帮到别人。
%{
#define GetSomething 1
%}
%typemap(out) bool %{
#if $symname == 1
if (result) {
return Py_FromString(arg0->data());
} else {
return Py_None;
}
#endif
%}https://stackoverflow.com/questions/25650761
复制相似问题