Wrapping C++ class with SWIG, Mac OS X


, (related to previous thread on wrapping C/C++ in Python, trying the SWIG approach.) Trying to map a C++ class to python, one method for now. Running the following commands to "compile": -------------------------------------- #!/usr/bin/env bash MOD_NAME=Wavelet swig -c++ -python ...
Posted On: Saturday 10th of November 2012 02:23:47 AM Total Views:  60
View Complete with Replies

RELATED TOPICS OF Python Programming PROGRAMMING LANGUAGE




enhancing/wrapping an existing instance of a duck

Basically I have an existing (maybe a rather large and complicated (existing) instance) that I want to add new member to. Cheers N Hacks/attempts follow: from math import sqrt ############ try2 ############ duck_obj = [ i*i for i in range(25) ] # OR a large sparse matrix # I "want" to an a useful property, eg length, and retain the ducks existing properties. # I COULD try... setattr(duck_obj,"length",lambda: sqrt(sum(*duck_obj))) print duck_obj.length() # returns 70 duck_obj[0]=70+71 print duck_obj.length() # returns 71 ############ try2 ############ # **BUT** I'd rather encapsulate a the original instance somehow. # I presume that I could define a class to do this somehow duck_obj = [ i*i for i in range(25) ] # OR a LargeSparseMatrix() dec = Vec(duck_obj) \t print dec.length() # returns 70 duck_obj[0]=70+71 # original "large and complicated duck instance" print dec.length() # returns 71 Any hints on how I need to define Vec so that any kind of duck_obj can be decorated/wrapped/encapsulated.
VIEWS ON THIS POST

52

Posted on:

Saturday 3rd November 2012
View Replies!

Re: wrapping C functions in python

SWIG is a program that automatically generates code to interface Python (and many other languages) with C/C++. If you plan to create lasting software libraries to be accessed from Python and C it is quite a robust way to do so. Essentially, you feed it header files, compile your code and the code generated by swig as a shared library, then import the functions like you would a normal python module. If all you need is to make some numerical code run faster it may be more of a learning curve then you bargain for. Perhaps trying NumPy is more appropriate. http://numpy.scipy.org/ -Brian On Wed, Apr 9, 2008 at 2:44 PM, Paul Anton Letnes wrote: > and thanks. > > > However, being a newbie, I now have to ask: What is SWIG I have heard the > name before, but haven't understood what it is, why I need it, or similar. > Could you please supply some hints > > > -Paul > > > Den 9. april. 2008 kl. 22.22 skrev Brian Cole: > > > > > > > > > > We use the following SWIG (www.swig.org) typemap to perform such > operations: > > > > %typemap(in) (int argc, char **argv) { > > if (!PySequence_Check($input)) { > > PyErr_SetString(PyExc_ValueError,"Expected a sequence"); > > return NULL; > > } > > $1 = PySequence_Length($input); > > $2 = (char**)alloca($1*sizeof(char*)); > > for (Py_ssize_t i = 0; i < $1; ++i) { > > PyObject *o = PySequence_GetItem($input, i); > > $2[i] = PyString_AsString(o); > > } > > } > > > > That one works for mapping a python sequence (such as a list) into the > > argc, argv arguments commonly passed into main. > > > > -Brian > > > > On Wed, Apr 9, 2008 at 2:13 PM, Paul Anton Letnes > > wrote: > > > > > etc. > > > > > > > > > I am a "scientific" user of Python, and hence have to write some > performance > > > critical algorithms. Right now, I am learning Python, so this is a > "newbie" > > > question. > > > > > > I would like to wrap some heavy C functions inside Python, specifically > a > > > wavelet transform. I am beginning to become aquainted with the functions > > > PyArg_ParseTuple() and Py_BuildValue(). However, I am unable to figure > out > > > how to pass Python list -> C function or C array -> return value in > Python. > > > I manage to build and run the C function, print to screen, pass string > as > > > argument, return an int, etc. The thing which is missing is the magic > > > array/list... > > > > > > > > >
VIEWS ON THIS POST

130

Posted on:

Sunday 4th November 2012
View Replies!

Python 2.6 and wrapping C libraries on Windows

I have read that Python extension modules must link to the same C run-time as the Python interpreter. This I can appreciate. But does this requirement extend to the C libraries an extension module wraps. The case in point is Pygame and SDL. The Pygame extension modules are built with distutils, so for Python 2.6 using Visual Studio 2008 should ensure the .pyd files link to msvcr90.dll. But SDL is built using Msys/MinGW and the configure/make tool chain. This fails when linking to msvcr90.dll since the small test programs configure builds lack manifest files. They fail to load msvcr90.dll, raising an R6034 error instead. So besides heap management and FILE pointers, is there any reason SDL, or any C dependency, needs to link to the same C run-time as Python If I ensure SDL frees memory it allocates and does not directly access a file opened by Python can I just use another C run-time such as msvcrt -- Lenard Lindstrom "%s@%s.%s" % ('len-l', 'telus', 'net')
VIEWS ON THIS POST

78

Posted on:

Sunday 4th November 2012
View Replies!

ANN: pywinauto 0.3.5 released - Moved to Metaclass control wrapping

0.3.5 release of pywinauto is now available. pywinauto is a set of open-source (LGPL) modules for using Python as a GUI automation 'driver' for Windows NT based Operating Systems (NT/W2K/XP). SourceForge project page: http://sourceforge.net/projects/pywinauto Download from SourceForge http://sourceforge.net/project/showf...roup_id=157379 Here is the list of changes from 0.3.4: 0.3.5 Moved to Metaclass control wrapping ------------------------------------------------------------------ 24-May-2006 * Moved to a metaclass implementation of control finding. This removes some cyclic importing that had to be worked around and other then metaclass magic makes the code a bit simpler. * Some of the sample files would not run - so I updated them so they would
VIEWS ON THIS POST

94

Posted on:

Monday 5th November 2012
View Replies!

wrapping a method function call?

I am instantiating a class A (which I am importing from somebody else, so I can't modify it) into my class X. Is there a way I can intercept or wrape calls to methods in A I.e., in the code below can I call x.a.p1() and get the output X.pre A.p1 X.post Many TIA! Mark class A: # in my real application, this is an imported class # that I cannot modify def p1(self): print 'A.p1' class X: def __init__(self): self.a=A() def pre(self): print 'X.pre' def post(self): print 'X.post' x=X() x.a.p1() -- Mark Harrison Pixar Animation Studios
VIEWS ON THIS POST

131

Posted on:

Wednesday 7th November 2012
View Replies!

Bug in Python class static variable?

I am trying to define a class static variable. But the value of the static variable seems to be only defined inside the file that the class is declared. See the code below. When I run "python w.py", I got: 000=======> World 001=======> World 002=======> Not Initialized 003=======> Not Initialized 004=======> Not Initialized 005=======> World Looks like even though the class variable "ClassW.w_classStaticVar" was set inside "startup()", the value never carried over to functions in "a.py". Is this a bug in Python's static variable handling. I am running Python 2.4.4. Ben #===== file: w.py ======== from a import * class ClassW: w_classStaticVar = "Not Initialized" def initA(self): print "001=======>", ClassW.w_classStaticVar obj = ClassA() obj.init2() print "005=======>", ClassW.w_classStaticVar def startup(): ClassW.w_classStaticVar = " World" wo = ClassW() print "000=======>", ClassW.w_classStaticVar wo.initA() if __name__ == '__main__': startup() #===== file: a.py ======== from w import * class ClassA: def __init__(self): print "002=======>", ClassW.w_classStaticVar def init2(self): print "003=======>", ClassW.w_classStaticVar w = ClassW() print "004=======>", ClassW.w_classStaticVar
VIEWS ON THIS POST

46

Posted on:

Wednesday 7th November 2012
View Replies!

Re: string formatter %x and a class instance with __int__ cannothandle long

En Thu, 21 Jun 2007 05:36:42 -0300, Kenji Noguchi escribi: > I confirmed that "%08x" % int(y) works. And yes, I'm hoping so. > It actually works that way if the v is less than or equal to 0x7ffffffff. > >> It is a bug, at least for me, and I have half of a patch addressing it. >> As a workaround, convert explicitely to long before formatting. > > I'm interested in your patch. What's the other half still missing As you have seen, PyString_Format doesn't handle well objects that can be converted to long but are not longs themselves; I've modified that function, but PyUnicode_Format has a similar problem, that's "the other half". Maybe this weekend I'll clean those things and submit the patch. -- Gabriel Genellina
VIEWS ON THIS POST

236

Posted on:

Wednesday 7th November 2012
View Replies!

Create a new class on the fly

Is this possible or is there a better way. I need to create a new class during runtime to be used inside a function. The class definition and body are dependant on unknows vars at time of exec, thus my reasoning here. class PosRecords(tables.IsDescription): class A(object): self.__init__(self, args): ........ def mkClass(self, args): eval( "class B(object): ...") #definition on B is dependant on dynamic values in string ......do stuff with class
VIEWS ON THIS POST

63

Posted on:

Wednesday 7th November 2012
View Replies!

New Module: CmdLoop - Base class for writing simple interactivecommand loop environments.

Code available here: http://littlelanguages.com/web/softw...les/cmdloop.py Base class for writing simple interactive command loop environments. CommandLoop provides a base class for writing simple interactive user environments. It is designed around sub-classing, has a simple command parser, and is trivial to initialize. Here is a trivial little environment written using CommandLoop: import cmdloop class (cmdloop.CommandLoop): PS1='hello>' @cmdloop.aliases('hello', 'hi', 'hola') @cmdloop.shorthelp('say hello') @cmdloop.usage('hello TARGET') def helloCmd(self, flags, args): ''' Say hello to TARGET, which defaults to 'world' ''' if flags or len(args) != 1: raise cmdloop.InvalidArguments print >> self.OUT, ' %s!' % args[0] @cmdloop.aliases('quit') def quitCmd(self, flags, args): ''' Quit the environment. ''' raise cmdloop.HaltLoop ().runLoop() Here's a more complex example: import cmdloop class Goodbye(cmdloop.CommandLoop): PS1='hello>' def __init__(self, default_target = 'world'): self.default_target = default_target self.target_list = [] @cmdloop.aliases('hello', 'hi', 'hola') @cmdloop.shorthelp('say hello') @cmdloop.usage('hello [TARGET]') def helloCmd(self, flags, args): ''' Say hello to TARGET, which defaults to 'world' ''' if flags or len(args) > 1: raise cmdloop.InvalidArguments if args: target = args[0] else: target = self.default_target if target not in self.target_list: self.target_list.append(target) print >> self.OUT, ' %s!' % target @cmdloop.aliases('goodbye') @cmdloop.shorthelp('say goodbye') @cmdloop.usage('goodbye TARGET') def goodbyeCmd(self, flags, args): ''' Say goodbye to TARGET. ''' if flags or len(args) != 1: raise cmdloop.InvalidArguments target = args[0] if target in self.target_list: print 'Goodbye %s!' % target self.target_list.remove(target) else: print >> self.OUT, \ "I haven't said hello to %s." % target @cmdloop.aliases('quit') def quitCmd(self, flags, args): ''' Quit the environment. ''' raise cmdloop.HaltLoop def _onLoopExit(self): if len(self.target_list): self.pushCommands(('quit',)) for target in self.target_list: self.pushCommands(('goodbye', target)) else: raise cmdloop.HaltLoop Goodbye().runLoop()
VIEWS ON THIS POST

119

Posted on:

Wednesday 7th November 2012
View Replies!

Passing arguments to subclasses

May I ask a simple newbie question, which I presume is true, but for which I can't readily find confirmation: Let's say I have a parent class with an __init__ method explicitly defined: class ParentClass(object): def __init__(self, keyword1, keyword2): etc and I subclass this: class ChildClass(ParentClass): # No __init__ method explicitly defined Now I presume that I can instantiate a child object as: child = ChildClass(arg1, arg2) and arg1, arg2 will be passed through to the 'constructor' of the antecedent ParentClass (there being no overrriding __init__ method defined for ChildClass) and mapping to keyword1, keyword2 etc. Have I understood this correctly , John Dann wrote: > May I ask a simple newbie question, which I presume is true, but for > which I can't readily find confirmation: > > Let's say I have a parent class with an __init__ method explicitly > defined: > > class ParentClass(object): > def __init__(self, keyword1, keyword2): > etc > > and I subclass this: > > class ChildClass(ParentClass): > # No __init__ method explicitly defined > > Now I presume that I can instantiate a child object as: > > child = ChildClass(arg1, arg2) > > and arg1, arg2 will be passed through to the 'constructor' of the > antecedent ParentClass (there being no overrriding __init__ method > defined for ChildClass) and mapping to keyword1, keyword2 etc. > > Have I understood this correctly Yes, but... The nice things about Python is that you can use the interactive interpreter to test such things in an instant. (And not have to wait for a response from python-list. Like this: >>> class ParentClass(object): .... def __init__(self, keyword1, keyword2): .... print 'ParentClass.__init__ called with', keyword1, keyword2 .... >>> class ChildClass(ParentClass): .... pass .... >>> child = ChildClass(123,456) ParentClass.__init__ called with 123 456 >>> Gary Herron
VIEWS ON THIS POST

373

Posted on:

Wednesday 7th November 2012
View Replies!

should I put old or new style classes in my book?

Hi , I am working on a revised edition of How To Think Like a Computer Scientist, which is going to be called Think Python. It will be published by Cambridge University Press, but there will still be a free ...
VIEWS ON THIS POST

67

Posted on:

Saturday 10th November 2012
View Replies!

About Michele Simionato's "classinitializer" decorator

Hi all. I just send this post as a comment to the third part of Michele Simionato's article about metaprogramming techniques at: http://www.ibm.com/developerworks/li...GX03&S_CMP=ART I found extremely useful the classinitializer "trick". I was thinking over the caveat not to call a ...
VIEWS ON THIS POST

66

Posted on:

Saturday 10th November 2012
View Replies!

Decorator metaclass

I would like to create a Decorator metaclass, which automatically turns a class which inherits from the "Decorator" type into a decorator. A decorator in this case, is simply a class which has all of its decorator implementation inside ...
VIEWS ON THIS POST

46

Posted on:

Saturday 10th November 2012
View Replies!

Re: Dynamic subclassing ?

Karlo Lozovina <_karlo_@_mosor.net> wrote: > manatlan wrote: >> I can't find the trick, but i'm pretty sure it's possible in an easy >> way. > It's somewhat easy, boot looks ugly to me. Maybe someone has a more > elegant ...
VIEWS ON THIS POST

62

Posted on:

Saturday 10th November 2012
View Replies!

array in class

class A: this_is_original_variable_only_for_one_inctance = 0 def __init__(self, v): self.this_is_original_variable_only_for_one_inctance = v class B: this_is_common_for_all_instances = [] def __init__(self, v): self.this_is_common_for_all_instances.append(v) ---------------- now I can create some instances of B, but all of them have the same array, why if I ...
VIEWS ON THIS POST

168

Posted on:

Saturday 10th November 2012
View Replies!

Re: New-style classes and special methods

> Yes, special methods populate the slots in the structures which Python > uses to represent types. Objects/typeobject.c in the Python source > distribution does the hard work, particularly in function type_new
VIEWS ON THIS POST

68

Posted on:

Saturday 10th November 2012
View Replies!

Re: conditionally creating functions within a class?

On 5/26/07, Steve Holden wrote: > I have taken the liberty of copying this back to the list, since other > people may have stringer opinions than I on your approach. > > Frankly, I wouldn't worry about the ...
VIEWS ON THIS POST

84

Posted on:

Saturday 10th November 2012
View Replies!

Re: @classmethod question

On 4/23/08, Ivan Illarionov (ivan.illarionov@gmail.com) wrote: >On 24 \t, 07:27, Scott SA wrote: >> I'm using the @classemethod decorator for some convenience methods and for > >It would make sense to separate instance-level and class-level >behaviour with additional 'objects' ...
VIEWS ON THIS POST

74

Posted on:

Saturday 10th November 2012
View Replies!

SWIG (Python) - "no constructor defined" for concrete class

Yet another SWIG question (YASQ!). I'm having a problem with using an abstract base class. When generating the Python bindings, SWIG thinks that all the concrete classes that derive from this abstract class are abstract too and won't create the ...
VIEWS ON THIS POST

120

Posted on:

Saturday 10th November 2012
View Replies!

class level properties

I'm trying to construct read-only variables at the class level. I've been unsuccessful. Any suggestions Mixing @classmethod and @property doesn't appear to produce workable code. Ditto for mixing @classmethod and __getattr__. (The property approach compiles, but execution says that you ...
VIEWS ON THIS POST

38

Posted on:

Saturday 10th November 2012
View Replies!