Re: Writing to stdout / stderr from C extensions

Robert Heller <[email protected]> Tue, 8 Jun 2021 13:17:45 -0400 (EDT)
Newsgroups gmane.comp.programming.swig
Organization Deepwoods Software
Message-ID <[email protected]>
At Tue, 8 Jun 2021 11:23:01 -0500 kesmit <[email protected]> wrote:

> 

> I've had an issue in my SWIG wrapped C extensions that I've never figured
> out how to make work across multiple scripting languages. If my extension
> writes something to stdout or stderr, it doesn't go to the same file
> object as printing from Python / R / Lua / etc. So any sort of tools that
> depend on capturing those messages don't work properly. I was wondering if
> there was some trick in SWIG that can be used to make writing to stdout /
> stderr work compatibly with the scripting language being used.

I wrap for Tcl, but the same methodology should translate to other scripting 
languages.  There are two options:

1) don't do any I/O to the std* streams in your extension -- do ALL of your
std* stream I/O (other than maybe debugging messages) at the scripting
language level.  Maybe that might mean returning more info from the extension. 
In one of my extensions, the "low-level" C++ code wants to write errors to an 
error output streams.  I use an instance of std::ostringstream and convert 
that to a string when the C++ function returns and append it to the return 
returned to the scripting language.

2) if your extension must perform I/O, use the C API of the scripting language 
for that I/O.  (In the sase of Tcl, this would be Tcl's Tcl_Channel API 
functions, which would include Tcl_GetStdChannel, etc.)

> 
> Kevin Smith
> [email protected]
> 
> 
> 
> 
> 
> 
> _______________________________________________
> Swig-user mailing list
> [email protected]
> https://lists.sourceforge.net/lists/listinfo/swig-user
> 
> 

-- 
Robert Heller             -- Cell: 413-658-7953 GV: 978-633-5364
Deepwoods Software        -- Custom Software Services
http://www.deepsoft.com/  -- Linux Administration Services
[email protected]       -- Webhosting Services