Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 296235
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T06:31:48+00:00 2026-05-12T06:31:48+00:00

I am attempting to create python bindings for some C++ code using swig. I

  • 0

I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for methods like the following:

class Player {
public:
  void entity(Entity* entity);
  Entity* entity() const;
};

I tried creating a property using the python property function but it seems that the wrapper classes swig generates are not compatible with it at least for setters.

How do you create properties using swig?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T06:31:48+00:00Added an answer on May 12, 2026 at 6:31 am

    Ooh, this is tricky (and fun). SWIG doesn’t recognize this as an opportunity to generate @property: I imagine it’d be all too easy to slip up and recognize lots of false positives if it weren’t done really carefully. However, since SWIG won’t do it in generating C++, it’s still entirely possible to do this in Python using a small metaclass.

    So, below, let’s say we have a Math class that lets us set and get an integer variable named “pi”. Then we can use this code:

    example.h

    #ifndef EXAMPLE_H
    #define EXAMPLE_H
    
    class Math {
     public:
        int pi() const {
            return this->_pi;
        }
    
        void pi(int pi) {
            this->_pi = pi;
        }
    
     private:
        int _pi;
    };
    
    #endif
    

    example.i

    %module example
    
    %{
        #define SWIG_FILE_WITH_INIT
        #include "example.h"
    %}
    
    [essentially example.h repeated again]
    

    example.cpp

    #include "example.h"
    

    util.py

    class PropertyVoodoo(type):
        """A metaclass. Initializes when the *class* is initialized, not
        the object. Therefore, we are free to muck around the class
        methods and, specifically, descriptors."""
    
        def __init__(cls, *a):
            # OK, so the list of C++ properties using the style described
            # in the OP is stored in a __properties__ magic variable on
            # the class.
            for prop in cls.__properties__:
    
                # Get accessor.
                def fget(self):
                    # Get the SWIG class using super. We have to use super
                    # because the only information we're working off of is
                    # the class object itself (cls). This is not the most
                    # robust way of doing things but works when the SWIG
                    # class is the only superclass.
                    s = super(cls, self)
    
                    # Now get the C++ method and call its operator().
                    return getattr(s, prop)()
    
                # Set accessor.
                def fset(self, value):
                    # Same as above.
                    s = super(cls, self)
    
                    # Call its overloaded operator(int value) to set it.
                    return getattr(s, prop)(value)
    
                # Properties in Python are descriptors, which are in turn
                # static variables on the class. So, here we create the
                # static variable and set it to the property.
                setattr(cls, prop, property(fget=fget, fset=fset))
    
            # type() needs the additional arguments we didn't use to do
            # inheritance. (Parent classes are passed in as arguments as
            # part of the metaclass protocol.) Usually a = [<some swig
            # class>] right now.
            super(PropertyVoodoo, cls).__init__(*a)
    
            # One more piece of work: SWIG selfishly overrides
            # __setattr__. Normal Python classes use object.__setattr__,
            # so that's what we use here. It's not really important whose
            # __setattr__ we use as long as we skip the SWIG class in the
            # inheritance chain because SWIG's __setattr__ will skip the
            # property we just created.
            def __setattr__(self, name, value):
                # Only do this for the properties listed.
                if name in cls.__properties__:
                    object.__setattr__(self, name, value)
                else:
                    # Same as above.
                    s = super(cls, self)
    
                    s.__setattr__(name, value)
    
            # Note that __setattr__ is supposed to be an instance method,
            # hence the self. Simply assigning it to the class attribute
            # will ensure it's an instance method; that is, it will *not*
            # turn into a static/classmethod magically.
            cls.__setattr__ = __setattr__
    

    somefile.py

    import example
    from util import PropertyVoodoo
    
    class Math(example.Math):
        __properties__ = ['pi']
        __metaclass__  = PropertyVoodoo
    
    m = Math()
    print m.pi
    m.pi = 1024
    print m.pi
    m.pi = 10000
    print m.pi
    

    So the end result is just that you have to create a wrapper class for every SWIG Python class and then type two lines: one to mark which methods should be converted in properties and one to bring in the metaclass.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 208k
  • Answers 208k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I don't know that the thread exit code is available… May 12, 2026 at 9:34 pm
  • Editorial Team
    Editorial Team added an answer Here is the best one I've found: http://www.scorm.com/wp-content/assets/scorm_ref_poster/RusticiSCORMPoster-large.pdf May 12, 2026 at 9:34 pm
  • Editorial Team
    Editorial Team added an answer It has nothing to do with parallel anything, but Indexed… May 12, 2026 at 9:34 pm

Related Questions

I have a problem when using Jython, but I can't seem to find a
Here is where I am at presently. I am designing a card game with
I'm coding the menu for an application I'm writing in python, using wxPython libraries
I am attempting to run a Python application within Apache (prefork) with WSGI in

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.