swig: how to pass void* into generic function

时间秒杀一切 提交于 2019-12-12 04:56:49

问题


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* );

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 );
}

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 );
    }
    ...
}

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.

Thank you,


回答1:


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?

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.



来源:https://stackoverflow.com/questions/15216447/swig-how-to-pass-void-into-generic-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!