Will Boyd | 31 Mar 16:39 2015
Picon

Exit SWIG-wrapped C/C++ routine without killing IPython kernel

Hello,

I am working on the OpenMOC code project which combines highly optimized algorithms written in C/C++ which are wrapped and exposed to Python using SWIG. Although some of our users write Python scripts to run simulations with OpenMOC, many are now beginning to increasingly use IPython Notebooks for a more interactive simulation experience.

One issue we have run into with IPython Notebook is that some of our C++ routines print a message and call the exit(1) to terminate execution if a error condition is reached. This seems to work fine for typical Python scripting, but unfortunately kills an IPython Notebook kernel.

Instead, we would like to kill execution if an error condition is met, but allow the IPython Notebook kernel to continue running so the user may adjust their simulation parameters to correct the issue without re-opening the Notebook.

Is there any way to terminate execution of wrapped C/C++ routines without killing IPython Notebook?

Thank you,

--
Will Boyd
Nuclear Science & Engineering
Massachusetts Institute of Technology
Email: wboyd <at> mit.edu
Cell: 423.413.8469
------------------------------------------------------------------------------
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/
_______________________________________________
Swig-user mailing list
Swig-user <at> lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/swig-user
Ahti Legonkov | 24 Mar 10:17 2015
Picon

Take ownership of object passed in as callback parameter

Consider this code:

// interface.hpp
struct Thing {
    void addRef();
    void release();
    uint refcount;
};

struct Callback {
   virtual void somethingHappened(Thing* thing) = 0;
};

struct S {
   static void doSomethingAsync(Callback* cb);
};

// interface.swg
%module(directors="1") Blah

%{
#include "interface.hpp"
%}

%feature("director") Callback;

%refobject   Thing "if ($this) { $this->addRef(); }"
%unrefobject Thing "if ($this) { $this->release(); }"

%include "interface.hpp"

// Generate wrapper:
# swig -c++ -java -outdir o -package com.bla interface.swg


I want ownership of "thing" to be transfered to the user of the wrapped lib when "somethingHappened" callback is called. 

At the moment the callback wrapper looks like this:

  public static void SwigDirector_Callback_somethingHappened(Callback jself, long t) {
    jself.somethingHappened((t == 0) ? null : new Thing(t, false));
  }

But I want it to be 

  public static void SwigDirector_Callback_somethingHappened(Callback jself, long t) {
    jself.somethingHappened((t == 0) ? null : new Thing(t, true));
  }

How do I do that? I know that for return values there is %newobject, but for parameters? Is there anything like that? 

--
lego
------------------------------------------------------------------------------
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/
_______________________________________________
Swig-user mailing list
Swig-user <at> lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/swig-user
alvin | 24 Mar 07:26 2015
Picon

Accessing structure members from python file which has been initialized in C

I'm new to python. I want to send a pointer to a structure from my C code to
a Python function, and then accessing the C structure from within Python. 

My structure is asa follows
*MyProject.i*
%module MyProject
%inline %{
struct argumentDetails
{
        char *argName;
        char *argType;
        int argSize;
};
struct SPythoned
{
        char *kerName;
        char *kerFileName;
        char *devType;
        int num_of_inputs;
        int num_of_outputs;
        struct argumentDetails *input_details;
        struct argumentDetails *output_details;
};
%}

*PyTest.py*
import MyProject

def TestObject(o):
        print "kenel name",o.kerName;
        print "kernel file name",o.kerFileName;
        print "dev type",o.devType;
        print "num_of_inputs ",o.num_of_inputs;
        for i in o.num_of_inputs:
                print "input ",o.input_details[i].argName

*main.cpp*
#include <stdio.h>
#include <Python.h>

extern "C"      // only needed when compiling in C++
{
        #include "MyProject_wrap.c"
}

// struct SPythoned is defined within MyProject_wrap.c just included above

void PythonTest(void)
{

        int i;
        Py_Initialize();        // Init Python
        SWIG_init();            // Initialise SWIG types
        init_MyProject();               // Init our project wrapped by Swig

        PyRun_SimpleString("import sys");
        PyRun_SimpleString("sys.path.append(\"./\")");

        SPythoned Object;
        PyObject *pMod, *pGlobalDict, *pFunc, *pResult, *pArg;

        Object.kerName = strdup("MatMatMul");
        Object.kerFileName = strdup("MatMatMul.cl");
        Object.devType = strdup("GPU");
        Object.num_of_inputs = 2;
        Object.num_of_outputs = 1;

        Object.input_details = (struct argumentDetails
*)malloc(Object.num_of_inputs * sizeof(argumentDetails));
        Object.output_details = (struct argumentDetails
*)malloc(Object.num_of_outputs * sizeof(argumentDetails));

        for(i=0;i<Object.num_of_inputs;i++)
        {
                Object.input_details[i].argName = strdup("a");
                Object.input_details[i].argType = strdup("float *");
                Object.input_details[i].argSize = 1024;
        }

        for(i=0;i<Object.num_of_outputs;i++)
        {
                Object.output_details[i].argName = strdup("b");
                Object.output_details[i].argType = strdup("float *");
                Object.output_details[i].argSize = 1024;
        }

        pMod = PyImport_ImportModule("PyTest"); // Load "PyTest.py" (it will
create a compiled version "PyTest.pyc")

        if (pMod)
        {

                pGlobalDict = PyModule_GetDict(pMod);   // Get main
dictionary

                if (pGlobalDict)
                {

                        pFunc = PyDict_GetItemString(pGlobalDict,
"TestObject");        // Look for function TestObject

                        if (pFunc)
                        {

                                pArg = SWIG_NewPointerObj((void*)&Object,
SWIGTYPE_p_SPythoned, 1);     // Get Python Object for our Structure Pointer

                                if (pArg)
                                {

                                        pResult =
PyObject_CallFunction(pFunc, "O", pArg);
                                        Py_CLEAR(pResult);
                                        printf("kername %s\tkerfilename
%s\tdevtype %s\n",Object.kerName,Object.kerFileName,Object.devType);
                                /*      for(i=0;i<2;i++)
                                        printf("object kername
%s\n",Object.ker_name[i]);*/
        //                              printf("\nobject kername
%s\n",Object.ker_names.ker_name[i]);

                                }
                        }
                }
        }

        Py_Finalize();
}

int main()
{
PythonTest();
return 0;
}

How can I access all the elements of a structre SPythoned from PyTest.py
file.?

--
View this message in context: http://swig.10945.n7.nabble.com/Accessing-structure-members-from-python-file-which-has-been-initialized-in-C-tp14306.html
Sent from the swig-user mailing list archive at Nabble.com.

------------------------------------------------------------------------------
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/
Yong Chen | 20 Mar 00:00 2015

swig 3.0.5

Hi,

I'm having a problem with swig3.0.5.

I downloaded the source code and am trying to build it. I can build the binary without problem. But when I try to build RPM, I get following error msg, basically "make check" fails:



make[1]: Entering directory `/rpmbuild/swig-3.0.5/CCache'
SWIG_LIB='.././../Lib' PATH=../..:$PATH SWIG='swig' CC='gcc' NOSOFTLINKSTEST='' ./test.sh
starting testsuite base
SUITE: base TEST: BASIC - Expected cache miss to be 1 got 2
cache directory                     ccache dir
cache hit                              0
cache miss                             2
autoconf compile/link                  1
files in cache                         3
cache size                             8 Kbytes
max cache size                     982.5 Mbytes
TEST FAILED
make[1]: *** [test] Error 1
make[1]: Leaving directory `/rpmbuild/swig-3.0.5/CCache'
make: *** [check-ccache] Error 2
error: Bad exit status from /tmp/rpm-tmp.5oFDFN (%check)


After some analysis, I found that the "ccache-swig" is giving trouble, it somehow increases the "cache miss" to 2 (from 0), after compiling test1.c for the first time. (also "files in cache" changed from 0 to 3, instead of from 0 to 1).

the Linux ccache doesn't have this problem.

Does anyone know what's the cause of this issue?

thanks,
Yong Chen


------------------------------------------------------------------------------
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/
_______________________________________________
Swig-user mailing list
Swig-user <at> lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/swig-user
Darryl L. Pierce | 19 Mar 20:59 2015
Picon

Swig wrappers and idempotency...

I have a need: if I get a C struct from Ruby, which is wrapped for me by
Swig, more than once I need those instances to be equal. IOW, if I do:

foo = Cproton.pn_transport_get_mine # both of these calls return a
bar = Cproton.pn_transport_get_mine # reference to the same C struct

foo == bar # right now returns false, but needs to return true

The above comparison, even though both foo and bar are wrappers around
the exact same underlying struct, always returns false since the wrapper
doesn't properly define .eql?, ==, etc.

Is there a way to tell Swig to use the underlying C struct and, if both
wrappers point to the same, return true in this case?

--

-- 
Darryl L. Pierce <mcpierce <at> gmail.com>
http://mcpierce.blogspot.com/
Famous last words:
   "I wonder what happens if we do it this way?"
------------------------------------------------------------------------------
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/
_______________________________________________
Swig-user mailing list
Swig-user <at> lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/swig-user
Christoph Egger | 19 Mar 14:20 2015

Re: %template and Warning 503

Hi!

Paweł Tomulik writes:
> Looks similar to
> http://swig.10945.n7.nabble.com/Unignore-all-and-template-td14147.html

It does! and the suggested workaround also works. Is it intended to
need both %template and %rename with essentially the same content?

  Christoph

--

-- 

------------------------------------------------------------------------------
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/
_______________________________________________
Swig-user mailing list
Swig-user <at> lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/swig-user
Christoph Egger | 19 Mar 12:42 2015

%template and Warning 503

Hi!

  I'm having trouble figuring out what I need to rename how to get this
to work. Below is a minimal example of the problem

Thanks!

  Christoph

====== test.i ======
%module test
%rename("%(utitle)s") "";
%include <std_map.i>

namespace std {
  %template(test) map<string, long*>;
}

===== output ======
% swig -guile -c++ test.i
test.i:5: Warning 503: Can't wrap class map< string,long * > unless renamed to a valid identifier.

------------------------------------------------------------------------------
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/
Witold E Wolski | 16 Mar 17:26 2015
Picon

Adding logging to swig generated methods in target language (java)

I would like to add a line of code (logging) to every swig generated
wrapper method in the target language.

So that the method :

  public long getMajorVersion() {
        return CamServerAPIueyeSwigJNI.DllVersion_getMajorVersion(swigCPtr,
this);
    }

looks like:

  public long getMajorVersion() {
        // my defined line of code here

        return CamServerAPIueyeSwigJNI.DllVersion_getMajorVersion(swigCPtr,
this);
    }

Is it possible to achieve it? I did some search but all I found,
related to java are the Java code typemaps

Help greatly appreciated.

--

-- 

Witold Eryk Wolski

------------------------------------------------------------------------------
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/
Nikolaj van Omme | 16 Mar 16:57 2015
Picon

NameError with Python SWIG trying to interface the cholmod library

Dear swig-users,

I'm trying to create a Python interface to the C Cholmod library, part of the SuiteSparse library (http://faculty.cse.tamu.edu/davis/suitesparse.html).

As I'm new to Swig, I don't know if this is a daunting task or not. I didn't find any website with this interface.

Compiling happens without trouble.

This is the error I get when I try to import the swig-generated"_cholmod.py":

====
Python 2.7.5+ (default, Feb 27 2014, 19:37:08)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import _cholmod
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_cholmod.py", line 99, in <module>
    class SuiteSparse_config_struct(_object):
  File "_cholmod.py", line 106, in SuiteSparse_config_struct
    __swig_setmethods__["malloc_func"] = __cholmod.SuiteSparse_config_struct_malloc_func_set
NameError: name '_SuiteSparse_config_struct__cholmod' is not defined
>>>
====

Where is this name defined? A quick grep doesn't return anything **before**  I try to import the extension but this **after** I try to import it:

====
grep -R -n  _SuiteSparse_config_struct__cholmod *

Binary file _cholmod.pyc matches
====

I'm using:

====
SWIG Version 3.0.5
Compiled with g++ [x86_64-unknown-linux-gnu]
Configured options: +pcre
====

and the latest cholmod library from SuiteSparse 4.4.3.

Here is a minimal example:

setup.py:

====
from distutils.core import setup, Extension

module1 = Extension('__cholmod',
    sources=['cholmod.i'],
    libraries=['cholmod', 'suitesparseconfig', 'blas', 'amd'],
    library_dirs=['/home/nikolaj/Documents/WORK/Dominique/suitesparse 4.4.1-1_ArchLinux/suitesparse-4.4.1-1-x86_64.pkg/usr/lib/'],
    include_dirs=['/home/nikolaj/Documents/WORK/Dominique/suitesparse 4.4.1-1_ArchLinux/suitesparse-4.4.1-1-x86_64.pkg/usr/include/'],
    swig_opts=['-I/home/nikolaj/Documents/WORK/Dominique/suitesparse 4.4.1-1_ArchLinux/suitesparse-4.4.1-1-x86_64.pkg/usr/include/'])

setup(name='_cholmod', version='0.1', ext_modules=[module1])
====

and I invoke it like this:

====
python setup.py build_ext --inplace
====

cholmod.i is:

====
/* -*- C -*- */
#ifdef SWIGPYTHON

%module _cholmod

%{
#define SWIG_FILE_WITH_INIT
#include "SuiteSparse_config.h"

#include "cholmod_config.h"
#include "cholmod_core.h"
#include "numpy/arrayobject.h"
%}

%feature("autodoc", "1");

%init %{
    import_array();
%}

%include "SuiteSparse_config.h
%include "cholmod_config.h"
%include "cholmod_core.h"

#endif
====

I suspect there is a problem with typedef and a C struct but after reading over and over tutorials, the official documentation, presentations I really don't know what I'm missing.

Could anyone help me here? Thanks a lot!

Best,
Nikolaj

------------------------------------------------------------------------------
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/
_______________________________________________
Swig-user mailing list
Swig-user <at> lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/swig-user
Kevin Smith | 16 Mar 15:58 2015
Picon

Destructors never getting called?

I have some wrappers written for Python and Lua that have destructors configured for all of the objects. 
However, it appears as though they never get called.  I looked in the generated wrappers for Python, and it
looks like the function is being properly put into the tp_dealloc slot.  I added a printf statement to the
wrapper to see when it would get printed and it never came out.  I also set a breakpoint in the destructor, but
it never gets hit.  Is there something else that I’m missing that would allow the objects to get cleaned up?

Kevin D Smith
Kevin.Smith <at> sas.com



------------------------------------------------------------------------------
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/
_______________________________________________
Swig-user mailing list
Swig-user <at> lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/swig-user
Christoph Egger | 16 Mar 15:38 2015

cstdint and stl container (iterators?)

Hi!

I have some to-be wrapped Interface with

class Foo {
public:
  Function* getFunction(uint64_t);
  bool hasFunctions() const {return functions.size() != 0;}
  std::map<uint64_t, Function*>::const_iterator beginFunctions();
  std::map<uint64_t, Function*>::const_iterator endFunctions();
};

and trying to get the (guile) wrapper for that to compile (I have also
tried all kinds of explicit instantiation of the template to no success
(uint64_t being unsigned long on 64bit linux I guess and cstdint.i
defines it as unsigned long long which is a different type?):

|  /home/siccegge/Project/frida/build/fridaGUILE_wrap.cxx:2414:10: error: no viable overloaded '='
|    result = (arg1)->beginFunctions();
|    ~~~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~
|  /home/siccegge/Project/frida/build/fridaGUILE_wrap.cxx:30:21: note: candidate function not
viable: no known conversion from
|        'std::map<uint64_t, Function *>::const_iterator' (aka '_Rb_tree_const_iterator<value_type>')
to 'const
|        SwigValueWrapper<std::_Rb_tree_const_iterator<std::pair<const unsigned long long, Function *> >
>' for 1st argument
|    SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs);
|                      ^
|  /home/siccegge/Project/frida/build/fridaGUILE_wrap.cxx:34:21: note: candidate function not
viable: no known conversion from
|        '_Rb_tree_const_iterator<pair<const unsigned long, [...]>>' to 'const
_Rb_tree_const_iterator<pair<const unsigned long long, [...]>>' for 1st
|        argument
|    SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; }

or (g++ instead of clang)

|  /home/siccegge/Project/frida/build/fridaGUILE_wrap.cxx:2414:10: error: no match for
‘operator=’ (operand types are
|  ‘SwigValueWrapper<std::_Rb_tree_const_iterator<std::pair<const long long unsigned int,
Function*> > >’ and ‘std::map<long unsigned int, Function*>::const_iterator
|  {aka std::_Rb_tree_const_iterator<std::pair<const long unsigned int, Function*> >}’)
|     result = (arg1)->beginFunctions();
|            ^
|  /home/siccegge/Project/frida/build/fridaGUILE_wrap.cxx:2414:10: note: candidates are:
|  /home/siccegge/Project/frida/build/fridaGUILE_wrap.cxx:30:21: note: SwigValueWrapper<T>&
SwigValueWrapper<T>::operator=(const SwigValueWrapper<T>&) [with T =
|  std::_Rb_tree_const_iterator<std::pair<const long long unsigned int, Function*> >]
|     SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs);
|                       ^
|  /home/siccegge/Project/frida/build/fridaGUILE_wrap.cxx:30:21: note:   no known conversion for
argument 1 from ‘std::map<long unsigned int,
|  Function*>::const_iterator {aka std::_Rb_tree_const_iterator<std::pair<const long unsigned
int, Function*> >}’ to ‘const
|  SwigValueWrapper<std::_Rb_tree_const_iterator<std::pair<const long long unsigned int,
Function*> > >&’
|  /home/siccegge/Project/frida/build/fridaGUILE_wrap.cxx:34:21: note: SwigValueWrapper<T>&
SwigValueWrapper<T>::operator=(const T&) [with T =
|  std::_Rb_tree_const_iterator<std::pair<const long long unsigned int, Function*> >]
|     SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; }
|                       ^
|  /home/siccegge/Project/frida/build/fridaGUILE_wrap.cxx:34:21: note:   no known conversion for
argument 1 from ‘std::map<long unsigned int,
|  Function*>::const_iterator {aka std::_Rb_tree_const_iterator<std::pair<const long unsigned
int, Function*> >}’ to ‘const
|  std::_Rb_tree_const_iterator<std::pair<const long long unsigned int, Function*> >&’

Christoph

------------------------------------------------------------------------------
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/
_______________________________________________
Swig-user mailing list
Swig-user <at> lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/swig-user

Gmane