Calling external programs from D

Kyle Furlong kylefurlong at gmail.com
Wed Apr 12 01:32:51 PDT 2006


Lionello Lunesu wrote:
> pragma wrote:
>> In article <e1g3sr$212p$1 at digitaldaemon.com>, Lionello Lunesu says...
>>> Just some idea:
>>>
>>> Wouldn't it be nice if there were an "extern (System)" calling 
>>> convention that would start external programs?
>>>
>>> For example:
>>>
>>> #extern (System) int wget(...);
>>> #
>>> #int main() {
>>> #  return wget("http://whatever");
>>> #}
>>>
>>> This would boost productivity especially for D scripts. Only too 
>>> often I need a small, temporary program to process some data and I 
>>> wish I had the compilable source of wget/grep/utility-x at hand to 
>>> incorporate their functionality.
>>
>> Nice idea.  The (System) convention is really just a macro to wrap a 
>> call to
>> std.system() right?
> 
> It's in std.process, apparently, but that's the idea. It's just a little 
> less typing then
> 
> #import std.process;
> #int wget( char[] args )
> #{
> #  return system( "wget " ~ args );
> #}
> 
> and with an added feature that it can check the argument types and 
> convert them to (quoted) strings.
> 
>> If it helps, I recently came up with a solution to handle cross-platform
>> scripting using D.  It handles all the differences between Linux and 
>> Windows
>> shells, including handling forward and backward slash conventions.
> 
> Nice! Now imagine your code like this
> 
> #extern (System) {
> #  void build( char[] options, char[] path );
> #  void copy( char[] src, char[] dest );
> #  void del( char[] );
> #  void move( char[] src, char[] dest );
> #}
> 
> and calling them would invoke the same system calls.
> 
>>> Seems easy enough to implement using spawning/waiting. The program 
>>> can be declared with "..." or some defined arugments, but all 
>>> arguments to the function would have to be cast to char[] for passing 
>>> to the new process. Would of course be even cooler if the linker 
>>> could pull in the external program's main(), but I suppose that's a 
>>> bit tricky :)
>>
>> This is actually quite tricky to do - pull this off and you're 
>> half-way to
>> writing your own shell.  Using System() is probably more efficent in 
>> terms of
>> overhead and RAM/CPU usage.  Plus, you don't have to worry about 
>> trying to
>> emulate shell features like the current $path and command aliases.
> 
> Yeah, I thought about those problems too. Furthermore, might not even be 
> allowed in the GPL to link to wget this way :)
> 
> L.

Its not linking, all it is is syntactic sugar.



More information about the Digitalmars-d mailing list