Factories and other functions returning pointers

Kris Thielemans <[email protected]> Thu, 2 Dec 2021 22:21:22 +0000
Newsgroups gmane.comp.programming.swig
Message-ID <CAFNfyPmDq1JWsTbaF4Kj=nbc+Og3wiVLo_542qqkJt-xp4uYVg@mail.gmail.com>
Hi all



I'm trying to make our Python interface to STIR friendlier w.r.t. derived
classes. Many of our C++ functions return a bare pointer to the base class.



class A;

class A1: public A;

class A2: public A;



class B

{

  A const * some_function() const;

};



It'd be great if in Python, the result of B::some_function() would be
actually of the appropriate type (e.g. A1), as there is no way to downcast
in Python.



I looked in the use of %factory. This is intended for "factory" functions
that create a new object. It then occurred to me that nothing in the
%factory mechanism seems to require that the result is a new object.
Indeed, using %factory for some_function() seems to work perfectly fine
(although I'm wondering about ownership).



%factory(A const* some_function, A1, A2);



This generates



typemap(out) A const* some_function{ … }



which handles the downcasting. Great! So then I hoped to just do this for
all functions that return an A* (or A const*).



%factory(A const*, A1, A2);



Generating



typemap(out) A const* { … }



However, this typemap doesn't match the signature of the
B::some_function(). Am I doing something stupid? (This is my first foray
into typemaps, so the answer is probably "yes").



Any help appreciated.



Thanks!



Kris



PS: in fact, most of our functions return a shared_ptr<const A> or even
unique_ptr, but I have to work around those as SWIG doesn't handle
unique_ptr yet unfortunately. See %factory fails with %shared_ptr · Issue
#2110 · swig/swig (github.com) for more information on my struggles with
shared_ptr.

_______________________________________________
Swig-user mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/swig-user