swig:如何将void *传递给泛型函数 [英] swig: how to pass void* into generic function
问题描述
我有一个场景,我需要通过基于SWIG(版本1.3)实现的C ++< - > Python接口传递opaque void *指针。我可以在这样的常规函数中返回并接受void *:
I have scenario where I need pass around opaque void* pointers through my C++ <-> Python interface implemented based on SWIG (ver 1.3). I am able to return and accept void* in regular functions like this:
void* foo();
void goo( void* );
当我尝试使用泛型函数做同样的事情时问题开始了(这就是我真正需要的去做)。我能够处理上面的foo场景,其功能基本上是这样的(从SWIG本身为上面的函数foo生成的代码中窃取):
The problems begins when I try to do the same using generic functions (and this is what I actually need to do). I was able to deal with "foo" scenario above with the function doing essentially something like this (stolen from code generated by SWIG itself for function foo above):
PyObject*
foo(...)
{
if( need to return void* )
return SWIG_NewPointerObj(SWIG_as_voidptr(ptr), SWIGTYPE_p_void, 0 | 0 );
}
我不相信这是最好的方法,但它有效。 goo场景更加麻烦。这里我需要处理一些通用输入,虽然我可以按照SWIG本身为上面的函数goo生成的代码中的示例实现转换逻辑:
I am not convinced this is the best way to do this, but it works. The "goo" scenario is much more troublesome. Here I need to process some generic input and while I can implement conversion logic following the example in the code generated by the SWIG itself for function goo above:
void
goo( PyObject* o )
{
...
if( o is actually void* ) { <==== <1>
void* ptr;
int res = SWIG_ConvertPtr( o, SWIG_as_voidptrptr(&ptr), 0, 0);
if( SWIG_IsOK(res) ) do_goo( ptr );
}
...
}
我没有在行< 1>中实现条件的任何方法。而对于其他类型,我可以使用如下函数:PyInt_Check,PyString_Check等,对于void *我没有选项可以这样做。在Python方面,它由具有PySwigObject类型的对象表示,虽然它肯定知道它包装了void *(如果我打印该值,我可以看到它)我不知道如何从PyObject *访问这些信息。
I do not have any way to implement condition in the line <1>. While for other types I can use functions like: PyInt_Check, PyString_Check etc, for void* I do not have the option to do so. On Python side it is represented by object with type PySwigObject and while it definitely knows that it wraps void* (I can see it if I print the value) I do not know how to access this information from PyObject*.
我很感激任何帮助找出处理这个问题的方法。
I would appreciate any help figuring out any way to deal with this problem.
谢谢你,
推荐答案
我是否正确地认为你基本上想要一些方法来测试传入的python对象是否为'void *'?大概这与测试它是否是指向任何东西的指针相同?
Am I right in thinking you essentially want some way of testing whether the incoming python object is a 'void*'? Presumably this is the same as testing if it is a pointer to anything?
如果是这样,那么使用boost :: shared_ptr(或其他指针容器)来保存你的通用对象?这需要一些C ++代码重写,所以可能不可行。
If so, what about using a boost::shared_ptr (or other pointer container) to hold your generic object? This would require some C++ code rewriting though, so might not be feasible.
这篇关于swig:如何将void *传递给泛型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!