uollas78@tiscali.it | 1 Jul 2007 15:46
Picon
Favicon

Directors C# inheritance problem

Hi, I'm exposing to swig (using C#) something like this:

%feature("director") Alfa;
class Alfa
{
public:
	Alfa() { }
	virtual ~Alfa() { }
	
protected:
	virtual void test() { }
};

%feature("director") Beta;
class Beta : public Alfa
{
public:
	Beta() { }
	virtual ~Beta() { }
};

and in my C# module I have:

public class Gamma : Beta
{
    public GammaXX() { }
    public void foo()
    {
        test();
    }
(Continue reading)

Yair Zafrany | 1 Jul 2007 20:18
Picon

swig 1.3.31 missing features

Hello Swig developers!
Looks like recent 1.3.31 is missing two important featutes:
1. Need to disable the class command.
    Even after using -nodefault, or -nodefaultctor, or %nodefault*,
    I am still getting a Swig command for each wrapped class. If the class doesn't define any constructors
    then the swig command simply complains about missing constructor.
    This is somewhat bothering if you happen to have a Tcl procedure by the same name.
    So an option to disable this would be appreciated
 
2. Somehow the -noobject option has dissappeared !? It's not always good to have the object oriented interface
    for each swig pointer that you create. Sometime you create trilions of objects and this has a very large
    memory cost.
    Any chance of making the -noobject flag back?
 
Thanks all for a great work!
-------------------------------------------------------------------------
This SF.net email is sponsored by DB2 Express
Download DB2 Express C - the FREE version of DB2 express and take
control of your XML. No limits. Just data. Click to get it now.
http://sourceforge.net/powerbar/db2/
_______________________________________________
Swig-user mailing list
Swig-user <at> lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/swig-user
David Baird | 2 Jul 2007 03:09
Picon

Problem with "bus error" when using SWIG directors

Hi,

I am having a problem with getting a "bus error" (on OS X) when
using directors with Python.

Here is a NullCallback class in C++ which is intended to be inherited from:

    class NullCallback
    {
      public:
        virtual ~NullCallback ();
        virtual void callme ();
    };

    NullCallback::~NullCallback () { }

    void
    NullCallback::callme ()
    {
        printf ("Oops: called the NullCallback!\n");
    }

And then there is some more C++ code to allow registering of a
callback (for the purpose of processing events):

    NullCallback *_callback = NULL;

    void
    set_event_callback (NullCallback *callback)
    {
        _callback = callback;
    }

    void
    notify_events_are_pending ()
    {
        if (_callback)
          {
            printf ("Attempting _callback->callme ()\n");
            _callback->callme ();
            printf ("Finished _callback->callme ()\n");
          }
    }

I have a SWIG ``mymodule.i`` file to accompany all this:

    %module(directors="1") mymodule
    %feature("director") NullCallback;

So, in Python, I write the following code:

    import mymodule

    class Callback(mymodule.NullCallback):

        def __init__(self):
            NullCallback.__init__(self)

        def callme(self):
            print 'Callback!!!'

    mycallback = Callback()
    set_event_callback(mycallback)

Now, to test things out, I then run the following code in Python:

    notify_events_are_pending()
    # >>>
    # Attempting _callback->callme ()
    # Callback!!!
    # Finished _callback->callme ()

I can even create threads and they work just fine, e.g.:

    import time

    class MyThread(threading.Thread):

        def __init__(self, period, lock):
            threading.Thread.__init__(self)
            self._period = period

        def run(self):
            while True:
                time.sleep(2)
                notify_events_are_pending()

    mythread = MyThread()
    mythread.start()

    # >>> (this message is repeated every 2 seconds):
    # Attempting _callback->callme ()
    # Callback!!!
    # Finished _callback->callme ()

Everything works great so far, but now I have a problem.  The source
of the callback will actually be some other process (outside of
Python and outside of my C++ code) which calls my C++ code and
causes it to call the callback.  Specifically, the source of the
callback will be CoreMIDI in Mac OS X and the callback is called
whenever MIDI data is received from an external device.  When I run
the program under those conditions, I get the following undesired output:

    Attempting _callback->callme ()
    Bus error
    <and then the program dies and returns to the shell>

I narrowed the problem down to this code generated by SWIG
(mymodule_wrap.cxx).  The bus error is generated on the line which says
``PyObject_CallMethod(swig_get_self(), (char *) "callme", NULL)``:

    void SwigDirector_NullCallback::callme() {
      if (!swig_get_self()) {
        Swig::DirectorException::raise("'self' uninitialized, maybe
you forgot to call NullCallback.__init__.");
      }
    #if defined(SWIG_PYTHON_DIRECTOR_VTABLE)
      const size_t swig_method_index = 0;
      const char * const swig_method_name = "callme";
      PyObject* method = swig_get_method(swig_method_index, swig_method_name);
      swig::PyObject_var result = PyObject_CallFunction(method, NULL, NULL);
    #else
      // Bus error is generated here:
      swig::PyObject_var result = PyObject_CallMethod(swig_get_self(),
(char *) "callme", NULL);
    #endif
      if (result == NULL) {
        PyObject *error = PyErr_Occurred();
        if (error != NULL) {
          Swig::DirectorMethodException::raise("Error detected when
calling 'NullCallback.callme'");
        }
      }
    }

If it helps, here is the version of SWIG I am running:

    SWIG Version 1.3.31

    Compiled with /usr/bin/g++-4.0 [i686-apple-darwin8.9.4]
    Please see http://www.swig.org for reporting bugs and further information

So, my question is: does anyone have some advice for how I could
effectively deal with this problem and eliminate the bus error?
Should I ask this question on a Python mailing list perhaps?

Thanks,
David

-------------------------------------------------------------------------
This SF.net email is sponsored by DB2 Express
Download DB2 Express C - the FREE version of DB2 express and take
control of your XML. No limits. Just data. Click to get it now.
http://sourceforge.net/powerbar/db2/
David Baird | 2 Jul 2007 04:32
Picon

Re: Problem with "bus error" when using SWIG directors

Okay, I found an answer already :-)  ...more or less...

I stumbled across a very helpful tutorial here:

    http://www.linuxjournal.com/article/3641
    Embedding Python in Multi-Threaded C/C++ Applications

On 7/1/07, David Baird <dhbaird <at> gmail.com> wrote:
> And then there is some more C++ code to allow registering of a
> callback (for the purpose of processing events):
>
>    NullCallback *_callback = NULL;
>
>    void
>    set_event_callback (NullCallback *callback)
>    {
>        _callback = callback;
>    }
>
>    void
>    notify_events_are_pending ()
>    {
>        if (_callback)
>          {
>            printf ("Attempting _callback->callme ()\n");
>            _callback->callme ();
>            printf ("Finished _callback->callme ()\n");
>          }
>    }

I rewrote this code as follows:

    #include <Python.h>

    PyThreadState *_main_thread_state;
    PyThreadState *_callback_thread_state;

    void
    init ()
    {
        Py_Initialize ();
        PyEval_InitThreads ();
        _main_thread_state = PyThreadState_Get ();
        PyEval_ReleaseLock ();

        // Create a thread to represent processes which generate callbacks
        // (e.g. the callback function of CoreMIDI)
        PyEval_AcquireLock ();
        _callback_thread_state = PyThreadState_New (_main_thread_state->interp);
        PyEval_ReleaseLock ();
    }

    void
    notify_events_are_pending ()
    {
        if (_callback)
          {
            PyEval_AcquireLock ();
            PyThreadState_Swap (_callback_thread_state);
            _callback->callme ();
            PyThreadState_Swap (NULL);
            PyEval_ReleaseLock ();
          }
        _events_are_pending = true;
    }

Now CoreMIDI can call "_callback->callme()" perfectly without any
bus errors.  But there is a new problem instead: now other threads
(from within Python) cannot call this code due to a deadlock.  Python
threads already have acquired the GIL (via ``PyEval_AcquireLock()``)
and thus if they try to call ``notify_events_are_pending()`` a
deadlock will occur when it also tries to acquire the GIL.

Therefore, I don't think this code is correct. A more correct way of
handling this situation involves the following steps (I think):

1. Create an official thread, solely for the purpose of calling
   ``_callback->callme()``

2. Other processes, such as CoreMIDI and Python threads use events,
   condition variables, or locks to interact with the callback thread (rather
   than calling the callback directly after acquiring the GIL)

I guess I will get around to trying to do that, but I'm lazy and
don't really want to :-P

Unfortunately, this complicates the ease of porting my code to various
languages (and OSs) which is what I hoped to avoid in the first place
by using SWIG.  Now I might also need to link with Boost (or some
other library, for threading support) as well as provide custom code
to manage interpreter locks for various languages.

Thoughts or suggestions?

-David

-------------------------------------------------------------------------
This SF.net email is sponsored by DB2 Express
Download DB2 Express C - the FREE version of DB2 express and take
control of your XML. No limits. Just data. Click to get it now.
http://sourceforge.net/powerbar/db2/
Robert Harakaly | 2 Jul 2007 13:53
Picon
Picon

Re: How to wrap C functions with swig 1.3

Hello Matthias

Thank you for your mail. You're right, the %exception is the correct 
directive to use. The mistake was on my side since I did not read well 
the documentation and I used $function instead of $action. Now it works 
well.

Thank you

Robert

Nitro wrote:
> Am 29.06.2007, 16:34 Uhr, schrieb Robert Harakaly 
> <robert.harakaly <at> cern.ch>:
>
>> Hello everybody,
>> [...]
>> Currently I found that in swig 1.3 the %except directive is deprecated.
>> In any case when I run swig with %except the macros are not in the
>> wrapper file. I am looking to the swig 1.3 documentation and I cannot
>> find anything which can replace the %except directive. The use of
>> %exception do not result in needed wrapping.
>
> I think %exception is the replacement for %except. Why does it not 
> work as expected? Where are the differences?
>
> -Matthias

-------------------------------------------------------------------------
This SF.net email is sponsored by DB2 Express
Download DB2 Express C - the FREE version of DB2 express and take
control of your XML. No limits. Just data. Click to get it now.
http://sourceforge.net/powerbar/db2/
Josh Cherry | 2 Jul 2007 16:05
Picon
Favicon

Re: How to wrap C functions with swig 1.3


On Fri, 29 Jun 2007, Robert Harakaly wrote:

> I have a problem with the Python interface for my C library because of
> the global interpreter lock (GIL) causing incorrect behavior in the
> multi threaded clients.
>
> After looking around on the Internet I found that if I wrap my C
> functions by Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros I'll
> get needed behavior. It was proposed to use the %except directive to
> wrap automaticaly my functions with these macros. It looks like follows:

I see you've received an answer about the use of %exception.  Note also 
that SWIG has a mechanism for dealing specifically with the thread issue 
you're dealing with (e.g., the -threads option).  I have no experience 
with it, but you can read about it in the CHANGES file.

Josh

-------------------------------------------------------------------------
This SF.net email is sponsored by DB2 Express
Download DB2 Express C - the FREE version of DB2 express and take
control of your XML. No limits. Just data. Click to get it now.
http://sourceforge.net/powerbar/db2/
Navnidhi Sharma | 2 Jul 2007 17:19

SWIGTYPE_p_void in C#

-----my.i-------

-------------------

 

%{

       struct EmpRec {

                   int   empno;

                   long  socno;

                   short depno;

       };

        void print(void* var) {

              printf("%s", (char*) var);

        }

%}

 

       struct EmpRec {

                   int   empno;

                   long  socno;

                   short depno;

       };

        void print(void* var) {

              printf("%s", (char*) var);

        }

 

 

-------------------

-------------------

C# code

-------------------

-------------------

            EmpRec e = new EmpRec();

            mydll.print((mydll.SWIGTYPE_p_void) e);

 

I got the following error.

 

 

            Error:Cannot convert type ' mydll.EmpRec' to ' mydll.SWIGTYPE_p_void'

 

 

 

Is there any way this can be resolved.

 

 

 

 

**********************************************************************

This communication and all information (including, but not limited to,

market prices/levels and data) contained therein (the "Information") is

for informational purposes only, is confidential, may be legally

privileged and is the intellectual property of ICAP plc and its affiliates

("ICAP") or third parties. No confidentiality or privilege is waived or

lost by any mistransmission. The Information is not, and should not

be construed as, an offer, bid or solicitation in relation to any

financial instrument or as an official confirmation of any transaction.

The Information is not warranted, including, but not limited, as to

completeness, timeliness or accuracy and is subject to change

without notice. ICAP assumes no liability for use or misuse of the

Information. All representations and warranties are expressly

disclaimed. The Information does not necessarily reflect the views of

ICAP. Access to the Information by anyone else other than the

recipient is unauthorized and any disclosure, copying, distribution or

any action taken or omitted to be taken in reliance on it is prohibited. If

you receive this message in error, please immediately delete it and all

copies of it from your system, destroy any hard copies of it and

notify the sender.

**********************************************************************

 

-------------------------------------------------------------------------
This SF.net email is sponsored by DB2 Express
Download DB2 Express C - the FREE version of DB2 express and take
control of your XML. No limits. Just data. Click to get it now.
http://sourceforge.net/powerbar/db2/
_______________________________________________
Swig-user mailing list
Swig-user <at> lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/swig-user
Mark Asbach | 2 Jul 2007 18:00
Picon
Picon
Favicon

Wrapping an interface that relies on iterators (targeting python)

Hi there,

I've got a class looking like

class Generator
{
public:

	typedef someabstractclass point;
	typedef someiteratorclassoverpoints iterator;

	iterator points_begin ();
	iterator points_end ();

	void somefunction (point);

};

Which means, a class holds some internal storage where a couple of  
'point' instances are stored. I can fetch an iterator that points to  
the first element and increment that iterator until it points to the  
last element. While iterating, I can invoke 'somefunction()' on the  
'point' object that my iterator currently points to. The  
corresponding code in C++ would look like:

Generator::iterator  point = some_generator.points_begin();
while (point != some_generator.points_end())
	some_generator.somefunction(*point);

Now I'd like to replicate that in Python, i.e. I'd like to iterate  
over all points BUT without creating a list or a tuple to copy them  
to. Ideally it would look like:

for point in some_generator.points():
   point.somefunction();
   #or
   some_generator.somefunction(point)

Now, how to do that? I would be very thankful for any pointers on  
documentation or sample code.

Thanks in advance,
Mark

--

-- 
Mark Asbach
Institut für Nachrichtentechnik, RWTH Aachen University
http://www.ient.rwth-aachen.de/cms/team/m_asbach

-------------------------------------------------------------------------
This SF.net email is sponsored by DB2 Express
Download DB2 Express C - the FREE version of DB2 express and take
control of your XML. No limits. Just data. Click to get it now.
http://sourceforge.net/powerbar/db2/
vincent vauchey | 2 Jul 2007 18:08
Picon

Problem to delete objects between python and C++. O.S:Windows

Hello everybody.    
I'm wrapping some class and methods from c++ to python, but I have some difficulties to delete objects.  
I will begin to explain my problem and what I tried to solve it.    

C++ code:  
"
Class Img      
{
Public :
Img(Pci &pci)      { …};
~Img()         
{ …  };
static void method()

cout<<"hello world"<<endl; 
}; 
… 
}; 

python code : 

>>>p= Pci(); 
>>>i=Img(p) 
>>>i1=Img(p) 
>>>i2=Img(p) #many  Img objects… 
… 
>>>foo=img(p)  
>>del p  
>>del i  


and there is a python crash…  

So I read the SWIG Documentation and I'm tried the following code: 
C++ code:  
"  
%pythonprepend Pci::Pci()  

            %{ 
            print "print PCI init" 
            self.list = [] 
            %}  

            %pythonprepend Pci::~Pci() 
            %{ 
            print "print PCI del"  
            for object in self.list: 
                        print "found 1 reference to an image"             

                        object.thisown = 0 #also I tried with :object.__swig_destroy__(object)#       
                        print "reference released to C++ level"  
            %}        

class Pci 

…  
};  
"  
python code :  

"  
>>>p= Pci();  
>>>i=Img(p)  
>>>pci.list.append(i)  
>>>i1=Img(p) 
>>> pci.list.append(i1)  
>>>i2=Img(p)  
>>> pci.list.append(i2) #many many Img objects…  
…  
>>>foo=img(p)  
>>> pci.list.append(foo)  
>>>i.thisown 

>>>del p 
found 1 reference to an image 
reference released to C++ level 
…  
>>>i.thisown  
0  
>>>i.method()  

and I obtain one crash because c++ object was deleted but python object is referenced.   

On the SWIG Documentations I read :  

"In this case, the object n is holding a reference to v internally. However, SWIG has no way to know that this has occurred. Therefore, Python still thinks that it has ownership of the object. Should the proxy object be destroyed, then the C++ destructor will be invoked and n will be holding a stale-pointer. If you're lucky, you will only get a segmentation fault.  

To work around this, it is always possible to flip the ownership flag.
For example,  >>> v.thisown = 0

It is also possible to deal with situations like this using typemaps--an advanced topic discussed later .    

"
So I thinck there is probably one solutions to resolve my problem, but I need your help.        


Best Regards.
Vincent.  


  

  

-------------------------------------------------------------------------
This SF.net email is sponsored by DB2 Express
Download DB2 Express C - the FREE version of DB2 express and take
control of your XML. No limits. Just data. Click to get it now.
http://sourceforge.net/powerbar/db2/
_______________________________________________
Swig-user mailing list
Swig-user <at> lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/swig-user
uollas78@tiscali.it | 2 Jul 2007 22:34
Picon
Favicon

Directors inheritance problem, help plz!!!

Hi, I'm reporting a problem exposed in the users mailing list, I hope 
someone can help me here...

I'm exposing to swig (using C#) something like this:

%feature("director") Alfa;
class Alfa
{
public:
Alfa() { }
virtual ~Alfa() { }

protected:
virtual void test() { }
};

%feature("director") Beta;
class Beta : public Alfa
{
public:
Beta() { }
virtual ~Beta() { }
};

and in my C# module I have:

public class Gamma : Beta
{
public Gamma() { }
public void foo()
{
test();
}
}

public static class Program
{
static void Run()
{
Gamma g = new Gamma();
g.foo();
}
}

This causes an access violation in the C++ code generated by swig, in
particular the problem is here:

SWIGEXPORT void SWIGSTDCALL CSharp_Alfa_testSwigExplicitAlfa(void *
jarg1) {
Alfa *arg1 = (Alfa *) 0 ;
SwigDirector_Alfa *darg = 0;

arg1 = (Alfa *)jarg1;
darg = dynamic_cast<SwigDirector_Alfa *>(arg1);
(darg)->testSwigPublic();
}

arg1 is a SwigDirector_Beta instance (not SwigDirector_Alfa) so the
dynamic_cast here returns null and the "testSwigPublic" call causes an
access violation.
Is there a fix for this problem?Why doesn't swig generate the
"CSharp_Beta_testSwigExplicitBeta" counterpart?

Help plz
Thanks

_______________________________________________________
Naviga e telefona senza limiti con Tiscali     
Scopri le promozioni Tiscali Adsl: navighi e telefoni senza canone Telecom

http://abbonati.tiscali.it/adsl/

-------------------------------------------------------------------------
This SF.net email is sponsored by DB2 Express
Download DB2 Express C - the FREE version of DB2 express and take
control of your XML. No limits. Just data. Click to get it now.
http://sourceforge.net/powerbar/db2/

Gmane