From e2d32f33b2b480ada4e96c666dd3664ba7df17c6 Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Mon, 6 Dec 2021 17:19:14 +0100 Subject: [PATCH] Add support for "cxxcode" typemap This allows injecting arbitrary code into the generated C++ classes and can be useful for defining extra constructors or operators, for example. --- Doc/Manual/C.html | 5 +++++ Source/Modules/c.cxx | 14 +++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/Doc/Manual/C.html b/Doc/Manual/C.html index e69d4f02b..414171dcf 100644 --- a/Doc/Manual/C.html +++ b/Doc/Manual/C.html @@ -496,6 +496,11 @@ area: 7.068583 Defines how to transform ctype value returned by a function to cxxouttype + + cxxcode + May contain arbitrary code that will be injected in the declaration of the C++ wrapper class corresponding to the given type. Ignored for non-class types. + +

C Typemaps, a Code Generation Walkthrough

diff --git a/Source/Modules/c.cxx b/Source/Modules/c.cxx index 005b53c45..90c015cc3 100644 --- a/Source/Modules/c.cxx +++ b/Source/Modules/c.cxx @@ -528,10 +528,22 @@ public: Printv(cxx_wrappers_.sect_decls, "class ", Getattr(n, "sym:name"), base_classes.get(), " {\n" - "public:\n", + "public:", NIL ); + // If we have any extra code, inject it. Note that we need a hack with an artificial extra node to use Swig_typemap_lookup(), as it needs a "type" attribute + // which the class node doesn't have. + scoped_dohptr dummy(NewHash()); + Setattr(dummy, "type", Getattr(n, "name")); + Setfile(dummy, Getfile(n)); + Setline(dummy, Getline(n)); + scoped_dohptr cxxcode(Swig_typemap_lookup("cxxcode", dummy, "", NULL)); + if (!cxxcode || *Char(cxxcode) != '\n') + Append(cxx_wrappers_.sect_decls, "\n"); + if (cxxcode) + Append(cxx_wrappers_.sect_decls, cxxcode); + class_node_ = n; dtor_wname_ = NULL; has_copy_ctor_ = false;