Bruce Kwan | 1 Oct 2002 02:58

Re: unsigned int and Python

Hi-

Thanks! I had typedef'd unsigned int to uint but I
neglected to include that typedef in the .i file. 

Bruce

----- Original Message ----- 
From: "David Beazley" <beazley <at> cs.uchicago.edu>
To: <b.h.kwan <at> ieee.org>
Cc: <swig <at> cs.uchicago.edu>
Sent: Monday, September 30, 2002 4:06 AM
Subject: [Swig] unsigned int and Python

> Bruce Kwan writes:
>  > Hi-
>  > 
>  > I have an unsigned int in my C++ class that I would
>  > like to shadow in Python using SWIG. However, I noticed that
>  > when I print the unsigned int class member from within Python
>  > after importing the shared library, it is being recognized 
>  > as a pointer to a unsigned int. 
> 
> An unsigned int class member should work fine (I just tried it and it
> seems to work). Are you sure this isn't a pointer, an array, or a
> reference of some kind?  Example?
> 
>  > I remember seeing in the 
>  > manual that the way unsigned int's are wrapped by SWIG 
>  > may need to be checked. Is there a way to make SWIG recognize 
(Continue reading)

Mitchell N Charity | 1 Oct 2002 06:16

Inline::SWIG

SWIG (http://www.swig.org/) does some nice parsing and glue generation.
In particular, it has rather broader coverage of C++ than Inline::CPP
(templates, operators, etc).

Perl's Inline (http://www.perldoc.com/cpan/Inline.html) is sometimes
more convenient.  Particularly for small bits of code.  Glue generation,
compilation, caching, and linking, all happen automagically.  And it
facilitates run-time code generation.

So I wrote an Inline::SWIG
  http://www.vendian.org/mncharity/dir3/inline/swig/
SWIG's glue inside Inline's process support.

It's a kludge.  A concept demo.  But I've found it useful.

Like other Perl Inline modules, one should be able to use it from
Python via zope-perl (http://www.zope.org/Wikis/zope-perl/FrontPage).

Fyi,
Mitchell Charity

The related mailinglists are
  http://mailman.cs.uchicago.edu/pipermail/swig/
  http://archive.develooper.com/inline%40perl.org/
_______________________________________________
Swig maillist  -  Swig <at> cs.uchicago.edu
http://mailman.cs.uchicago.edu/mailman/listinfo/swig

Ben Martin | 1 Oct 2002 07:21
Picon

wrapping libsigc++

Hi,
  Anyone know of example code that uses SWIG to wrap libsigc++ signals?
I'm looking to use guile as the scripting lang, but any examples that
use libsigc++ would be greatly appreciated.

Thanks
--

-- 
-----------------------------------------------------
In this world there are only two tragedies.  
One is not getting what one wants, 
and the other is getting it.
                -- Oscar Wilde
http://witme.sourceforge.net/libferris.web/

_______________________________________________
Swig maillist  -  Swig <at> cs.uchicago.edu
http://mailman.cs.uchicago.edu/mailman/listinfo/swig

Mathieu Tremblay | 1 Oct 2002 15:51

Swig - Python - Abstract class question

Hello,

    I'm having some problems with SWIG and Python, trying to extend an abstract class and override a pure virtual function.

    My base class is a CThread class which is defined in C++ and extended to
python using SWIG.  The class is an interface to easily create threads, the
process function must be defined in the child class and then when the run
function is called, the process function is executed in a separate thread.
Every function but the process function is already implemented.

class CThread
 {
 public:
      CThread();     //Constructor
      ~CThread();     //~Destructor
      virtual void process() = 0; //Pure virtual function to extend, thread function
      bool run();                          //calls the process() function in it
      bool suspend();
      bool resume();
      bool terminate();
 private:
      bool startThread();
      INT32 m_handle
};

The problem comes when I come to create a new class in python that inherits
from CThread.  Here is my python code
=
============== test.py =================
import my_module

class MyThread(my_module.CThread):
    def __init__(self):
        pass
    def process(self):
        print "hey"

a = MyThread()
a.run()
============================================
my_module is exposed to Python using SWIG.  When I try to execute this, I
get the following error :

    #############################################
    Traceback (most recent call last):
      File "U:\Alexandra\test\pythontool\martin.py", line 14, in ?
        a.run()
      File "U:\Alexandra\test\pythontool\hector.py", line 649, in run
        def run(*args): return apply(_hector.CThread_run,args)
    TypeError: Type error. Expected _p_CThread
    #############################################

Now, I know that I should be calling the hector.CThread.__init__(self) function in my constructor but since CThread is an abstract class, the constructor isn’t defined.  I noticed a CThreadPtr class in my module.py file, so I also tried the following :

 

==========python code==========

class MyThread(hector.CThread):

    def __init__(self):

        print "my thread initialized"

        pass

    def process(self):

      print "hey"

     

a = MyThread()

b = hector.CThreadPtr(a)

b.run()

===========================

           

            but I get an error about not knowing the “this” attribute

 

============error msg==========

my thread initialized

Traceback (most recent call last):

  File "U:\Alexandra\test\pythontool\martin.py", line 18, in ?

    b = hector.CThreadPtr(a)

  File "U:\Alexandra\test\pythontool\hector.py", line 659, in __init__

    self.this = this

  File "U:\Alexandra\test\pythontool\hector.py", line 641, in <lambda>

    __setattr__ = lambda self, name, value: _swig_setattr(self, CThread, name, value)

  File "U:\Alexandra\test\pythontool\hector.py", line 8, in _swig_setattr

    self.__dict__[name] = value.this

  File "U:\Alexandra\test\pythontool\hector.py", line 643, in <lambda>

    __getattr__ = lambda self, name: _swig_getattr(self, CThread, name)

  File "U:\Alexandra\test\pythontool\hector.py", line 19, in _swig_getattr

    raise AttributeError,name

AttributeError: this

==============================

 

            I have been told that it is easy to do what I want to do using Boost.Python, but I already invested some development time in SWIG and I would like to continue to use it.  Anybody can help ?

            Thanks a lot !

           
Mathieu Tremblay

Mark Phillips | 1 Oct 2002 18:11

TCL, win200, stdcall vs. cdecl

In MSVC 6.0

I'm trying to get a TCL extension to communicate with another C/C++ dll
that's using the __stdcall convention.  However, if I set the calling
convention to __stdcall (instead of __cdecl*), then the DLL extension can't
see any of the TCL library calls, such as Tcl_Eval().

What do I need to do?  Is there SWIG command line parameter I can use?  Do I
have to rebuild the TCL library?

Thanks,
Mark.

_______________________________________________
Swig maillist  -  Swig <at> cs.uchicago.edu
http://mailman.cs.uchicago.edu/mailman/listinfo/swig

Marcelo Matus | 1 Oct 2002 18:38
Picon

Re: Swig - Python - Abstract class question

Hmm, you can't "extend" a c++ virtual class like that
in python with swig, not as directly as in your example.

But here is a small work around:

Define a PYRef class like this:

-------------- pyref.h -----------

#include <Python.h>

class PYRef {
public:
PYRef() : pobj_(0) {}

PYRef(PyObject* pobj)
: pobj_(pobj)
{
Py_XINCREF(pobj_);
}

PYRef(const PYRef& pref)
: pobj_(pref.pobj_)
{
Py_XINCREF(pobj_);
}

~PYRef()
{
Py_XDECREF(pobj_);
}

PyObject* operator->() const
{
return pobj_;
}

operator PyObject*() const
{
return pobj_;
}

PyObject* in() const
{
return pobj_;
}

PYRef& operator=(const PYRef& pref)
{
if (pobj_ != pref.pobj_)
{
Py_XDECREF(pobj_);
pobj_ = pref.pobj_;
Py_XINCREF(pobj_);
}
return *this;
}
private:
PyObject* pobj_;
};

-------------- pyref.h -----------

and a python methow wrap like this:

-------------- pymethodwrap.h -----------

#include "pyref.h"

class PYMethodWrap
{
public:
PYMethodWrap(PyObject* PyFunc, PyObject* PyArgs = 0)
: method_(PyFunc), args_(PyArgs)
{
//
// We save the original thread state to use it later at run.
// If you don't save it, python will don't know which
// thread/intepret to use later.
//

tstate_ = PyThreadState_GET();

//
// We initialized the PyThreads. If they were initialized before,
// it doesn't hurt anybody.
//

PyEval_InitThreads();
}

void run()
{
//
// We acquire the original thread to execute the command.
//

if ((tstate_ != PyThreadState_GET()))
{
PyEval_AcquireThread(tstate_);
PyObject* result = PyEval_CallObject(method_.in(), args_.in());
PyDECREF(result);
PyEval_ReleaseThread(tstate_);
}
else
{
PyObject* result = PyEval_CallObject(method_.in(), args_.in());
PyDECREF(result);
}
}

private:
PYRef method_;
PYRef args_;
PyThreadState* tstate_;
};

-------------- pymethodwrap.h -----------

Then define a PYCThread like:

------------- pycthread.h -----------

class PYCThread : public CThread
{
public:

PYCThread(PyObject* PyFunc)
: _pymethod(PyFunc)
{
}

void process() {
_pymethod.run();
}

private:
PYMethodWrap _pymethod;
};

-------------- pycthread.h --------------

And use the following wrap:

-------------- pycthread.i -----------

%typemap(python,in) PyObject *PyFunc {
if (!PyCallable_Check($input))
{
PyErr_SetString(PyExc_TypeError, "Need a callable object");
return NULL;
}
$1 = $input;
}

#include "pycthread.h"

-------------- pycthread.i -----------

Then in python, after fixing all the possible
errors in the example code :), you can do:

import my_module

class MyThread(my_module.PYCThread):
def __init__(self):
my_module.PYCThread.__init__(lambda x = self : x.process())
pass
def process(self):
print "hey"

a = MyThread()

See the page

http://aspn.activestate.com/ASPN/Python/Reference/Products/ActivePython/python/ext/callingPython.html

for more discussion about what to do with the "result" and other things 
like error checking.

Also see the page:

http://www.python.org/doc/current/api/threads.html

for more information about how to "mix" threads when using the python C 
API library.
In fact, if you find a another way to do the same, please tell me, my 
example
is a very "raw" implementation that works, but there must be a more elegant
way.

Marcelo

Mathieu Tremblay wrote:

> Hello,
>
> I'm having some problems with SWIG and Python, trying to extend an 
> abstract class and override a pure virtual function.
>
> My base class is a CThread class which is defined in C++ and extended to
> python using SWIG. The class is an interface to easily create threads, the
> process function must be defined in the child class and then /when the run
> function is called, the process function is executed in a separate thread.
> /Every function but the process function is already implemented.
>
> class CThread
> {
> public:
> CThread(); //Constructor
> ~CThread(); //~Destructor
> virtual void process() = 0; //Pure virtual function to extend, thread 
> function
> bool run(); //calls the process() function in it
> bool suspend();
> bool resume();
> bool terminate();
> private:
> bool startThread();
> INT32 m_handle;¨
> };
>
> The problem comes when I come to create a new class in python that 
> inherits
> from CThread. Here is my python code
> =============== test.py =================
> import my_module
>
> class MyThread(my_module.CThread):
> def __init__(self):
> pass
> def process(self):
> print "hey"
>
> a = MyThread()
> a.run()
> ============================================
> my_module is exposed to Python using SWIG. When I try to execute this, I
> get the following error :
>
> #############################################
> Traceback (most recent call last):
> File "U:\Alexandra\test\pythontool\martin.py", line 14, in ?
> a.run()
> File "U:\Alexandra\test\pythontool\hector.py", line 649, in run
> def run(*args): return apply(_hector.CThread_run,args)
> TypeError: Type error. Expected _p_CThread
> #############################################
>
> Now, I know that I should be calling the hector.CThread.__init__(self) 
> function in my constructor but since CThread is an abstract class, the 
> constructor isn't defined. I noticed a CThreadPtr class in my 
> module.py file, so I also tried the following :
>
> ==========python code==========
>
> class MyThread(hector.CThread):
>
> def __init__(self):
>
> print "my thread initialized"
>
> pass
>
> def process(self):
>
> print "hey"
>
> a = MyThread()
>
> b = hector.CThreadPtr(a)
>
> b.run()
>
> ===========================
>
> but I get an error about not knowing the "this" attribute
>
> ============error msg==========
>
> my thread initialized
>
> Traceback (most recent call last):
>
> File "U:\Alexandra\test\pythontool\martin.py", line 18, in ?
>
> b = hector.CThreadPtr(a)
>
> File "U:\Alexandra\test\pythontool\hector.py", line 659, in __init__
>
> self.this = this
>
> File "U:\Alexandra\test\pythontool\hector.py", line 641, in <lambda>
>
> __setattr__ = lambda self, name, value: _swig_setattr(self, CThread, 
> name, value)
>
> File "U:\Alexandra\test\pythontool\hector.py", line 8, in _swig_setattr
>
> self.__dict__[name] = value.this
>
> File "U:\Alexandra\test\pythontool\hector.py", line 643, in <lambda>
>
> __getattr__ = lambda self, name: _swig_getattr(self, CThread, name)
>
> File "U:\Alexandra\test\pythontool\hector.py", line 19, in _swig_getattr
>
> raise AttributeError,name
>
> AttributeError: this
>
> ==============================
>
> I have been told that it is easy to do what I want to do using 
> Boost.Python, but I already invested some development time in SWIG and 
> I would like to continue to use it. Anybody can help ?
>
> Thanks a lot !
>
>
> Mathieu Tremblay
>

_______________________________________________
Swig maillist  -  Swig <at> cs.uchicago.edu
http://mailman.cs.uchicago.edu/mailman/listinfo/swig

Srivatsan Raghavan | 2 Oct 2002 02:04

swig runtime libs

hi all, i'm using swig to help set up using perl as an embedded 
scripting lang (tried python, but
since the python/c api is not reentrant it's not going to work for us)
and i'm pretty sure i need access to the SWIG runtime libraries,
is there anywhere they're available for windows?
i can d/l swig.exe for windows, but that's not sufficient
because from what i understand i need to access to the swig api (e.g. 
SWIG_* functions..
and the swig_type_info structure, and so on)
so .. are the swig runtime lib's available for download somewhere, or 
how can i generate them myself? the makefiles are unix-only, and i don't 
know of any dsp/dsw's for windows..
(or nmake files)

--vat

_______________________________________________
Swig maillist  -  Swig <at> cs.uchicago.edu
http://mailman.cs.uchicago.edu/mailman/listinfo/swig

Landshark | 2 Oct 2002 03:51

creating python objects from C++

Hello,

I've embedded the python interpreter into my c++ application successfully using
SWIG to wrap the classes.  I can run python commands from the C++ program using
function such as PyRun_SimpleString("doSomething()").  That works great.

However, I'm at the point where I need to start passing parameters to the
python functions *from C++*, where the functions are the wrapped C++ objects.

Does SWIG contain the functionality to do this?  I was looking through the
wrap.cxx file which got generated and it appears I could use something similar
to SWIG_NewPointerObj(...) and receive a PyObject in return to pass.

Would this be ok?

Only a wrap.cxx file gets generated, no header file, so I'm not too sure how
I'd gain access to these functions without writing my own header file which I'd
need to maintain manually.

On a side note, is anyone aware of how I could call SWIG_init() from another
source file (for embedding).

No matter what prototypes I create, it never seems to be able to find it.  So
instead I modify the wrap.cxx function and add: void tmpinit() { SWIG_init(); }
and then call this from my other source file, which works fine.

Anyway, I'd appreciate any help on the above matters, I'm stumped.

-dave

_______________________________________________
Swig maillist  -  Swig <at> cs.uchicago.edu
http://mailman.cs.uchicago.edu/mailman/listinfo/swig

Brian Ingerson | 2 Oct 2002 09:03

Re: Inline::SWIG

On 01/10/02 00:16 -0400, Mitchell N Charity wrote:
> SWIG (http://www.swig.org/) does some nice parsing and glue generation.
> In particular, it has rather broader coverage of C++ than Inline::CPP
> (templates, operators, etc).
> 
> Perl's Inline (http://www.perldoc.com/cpan/Inline.html) is sometimes
> more convenient.  Particularly for small bits of code.  Glue generation,
> compilation, caching, and linking, all happen automagically.  And it
> facilitates run-time code generation.
> 
> So I wrote an Inline::SWIG
>   http://www.vendian.org/mncharity/dir3/inline/swig/

Mitchell, This sounds awesome. You're a genius. Any chance of putting it
on CPAN? I could help you there.

I'm wondering, is it abstract enough so that we could just make it part of
Inline? We could let people pick what type of glue code they want.

I was thinking of writing my own glue code, sans XS, so that we could get rid
of XS altogether. We could do it without Makefile.PL too which I think would
make code generation/compiling very fast. Just:

   - Parse using your regex parser (instead of RecDescent)
   - Generate pure C glue
   - Feed it right to gcc

So now we'd have three different gluing options

   - SWIG
   - XS
   - IngyLine

Don't worry folks, I won't throw out the XS for good. It's way too stable.
But a faster option might be good for some applications.

Cheers, Brian
_______________________________________________
Swig maillist  -  Swig <at> cs.uchicago.edu
http://mailman.cs.uchicago.edu/mailman/listinfo/swig

William S Fulton | 2 Oct 2002 10:24
Picon
Favicon
Gravatar

Re: swig runtime libs

> hi all, i'm using swig to help set up using perl as an embedded
> scripting lang (tried python, but
> since the python/c api is not reentrant it's not going to work for us)
> and i'm pretty sure i need access to the SWIG runtime libraries,
> is there anywhere they're available for windows?
> i can d/l swig.exe for windows, but that's not sufficient
> because from what i understand i need to access to the swig api (e.g.
> SWIG_* functions..
> and the swig_type_info structure, and so on)
> so .. are the swig runtime lib's available for download somewhere, or
> how can i generate them myself? the makefiles are unix-only, and i don't
> know of any dsp/dsw's for windows..
> (or nmake files)
I'm afraid not. There is some work going on to update libtool which would
theoretically enable us to build the Windows runtime libraries using Unix
tools. There are some makefiles for building Windows (static) runtime
libraries with Visual Studio in SWIG-1.1. I'd suggest downloading it and
adapting them for SWIG-1.3, it shouldn't involve any rocket science :)

I think you can also just define -DSWIG_NOINCLUDE when compiling all but one
of your modules. You should then be able to link all your modules together
as then the runtime library functions only get compiled into one module.

Cheers
William

_______________________________________________
Swig maillist  -  Swig <at> cs.uchicago.edu
http://mailman.cs.uchicago.edu/mailman/listinfo/swig


Gmane