proc str2hex { string } {
set str [binary scan $string H* hex]
puts $hex
regsub -all (..) $hex {\1 } t1
set res [format "%s" $t1 ]
return $res
proc hex2str { $hex } {
puts "HIIHI"
foreach c [split $$hex ""] {
if {![string is xdigit $c]} {
return "#invalid $$hex"
}
}
set hexa [binary format H* $$hex]
return $hexa
}
}
The above is simple code for conversion of string to hexadecimal.I have made nested proc,where a hex from "set str [binary scan $string H* hex]" script is taken as input so as to re -convert the hex to string .Plz help me .
You shouldn't normally nest procedures inside procedures in Tcl; the results of it are not what you're expecting. Currently, the Tcl proc command takes almost no notice of the context in which it is called (except for knowing what the current namespace is), and in particular it does not affect what the “inner” procedure sees for variables.
What's more, proc is an ordinary command (that happens to create another command) and must actually be called for it to do anything. Putting it after the only return in a procedure will guarantee that it has no effect at all. Tcl's very simple-minded (and predictable) that way.
Finally, it's inadvisable to put $ in a variable name. It's legal, but the syntax for accessing it is awkward (in your case, it would be ${$hex}).
If you really want local procedure-like things, consider using apply and a lambda term. They were introduced in Tcl 8.5.
If you're using Tcl 8.6 (recommended now) then you've got some more elegant ways of doing these two operations:
proc str2hex {string {encoding "utf-8"}} {
binary scan [encoding convertto $encoding $string] cu* bytes
return [lmap value $bytes {format %02x $value}]
}
proc hex2str {hex {encoding "utf-8"}} {
return [encoding convertfrom $encoding [binary format H* [join $hex ""]]]
}
(The encoding needs to be specified as otherwise there isn't a unique mapping between bytes — which binary scan and binary format work with — and characters. But we can set a sensible default.)
Related
I have below dummy program,
proc main2 {} {
set mainVar 100
proc subproc1 {} {
puts $mainVar
}
subproc1
}
main2
it throws an error can't read "mainVar": no such variable. my question is if I declare a variable (i.e mainVar )in proc isn't that variable should be accessible everywhere inside that proc? why it can't accessible in another proc which is declared inside mainproc proc? please put some light on this
Tcl's procedures do not nest; there is no shared scope at all. The main reason for declaring a procedure inside another one is if you are doing some kind of code generation in the outer procedure (whether of the name, the variable list or the body).
Now, you can simulate a read-only version like this (simplified version; a full-service variant is a lot more complex):
proc closure {name arguments body} {
set vars [uplevel 1 {info locals}]
set prologue {}
foreach v $vars {
upvar 1 $v var
append prologue [list set $v $var] ";"
}
uplevel 1 [list proc $name $arguments $prologue$body]
}
proc main2 {} {
set mainVar 100
closure subproc1 {} {
puts $mainVar
}
subproc1
}
main2
I'll leave making it work correctly with global and arrays (as well as all the other nuances of doing this job properly) as exercises for the reader.
Please i want to creat a program/function in VC++ that allow me to run an EXE file and receive return value from it.
My EXE file tht i want to run is a console Application, it need two argument Arg1 (String) and Arg2 (Float), and return an OutPut (Float).
Something like :
OutPut = MyEXEFile.exe Arg1 Arg2
Command-line arguments come in only one data type: array of C-style string.
Input and output come in only one data type: stream of bytes.
You can supply any command-line and redirection the output if you use CreateProcess from the <windows.h> header file. Other data types such as float will need to be handled the same way you would handle them in a data file.
Here is an example on MSDN: Creating a Child Process with Redirected Input and Output
I find the solution, this is work fine for me, i test it, and it work well.
This is the link of the page where i find the solution, i fixe some errors, and now it ready for implement.
http://www.codeproject.com/Articles/10134/Execute-a-Console-Application-From-VC?fid=172409&fr=26#xx0xx
This is the exemple we need to execute. PS: this line is not a part of the our program, it's just here to explain the algorithm:
MyEXEFile.exe Arg1 Arg2 > sResult
The "MyEXEFile.exe" take two arguments (Arg1 and Arg2) and return a value in the sResult Variable.
Let us program this exemple with Visual C++ using CreatProcess :
CString ExePath="C:\\MyEXEFile.exe";
CString arg1="2";
CString arg2="3";
CString sResult="";
CString strCommandLine = ExePath + " " + arg1 + " " + arg2;
// Call the ExecuteExternalFile function
sResult = ExecuteExternalFile(strCommandLine);
This is the Function who will read the output of MyEXEFile.exe File :
CString ExecuteExternalFile(CString csExecute)
{
SECURITY_ATTRIBUTES secattr;
ZeroMemory(&secattr,sizeof(secattr));
secattr.nLength = sizeof(secattr);
secattr.bInheritHandle = TRUE;
HANDLE rPipe, wPipe;
//Create pipes to write and read data
CreatePipe(&rPipe,&wPipe,&secattr,0);
//
STARTUPINFO sInfo;
ZeroMemory(&sInfo,sizeof(sInfo));
PROCESS_INFORMATION pInfo;
ZeroMemory(&pInfo,sizeof(pInfo));
sInfo.cb=sizeof(sInfo);
sInfo.dwFlags=STARTF_USESTDHANDLES;
sInfo.hStdInput=NULL;
sInfo.hStdOutput=wPipe;
sInfo.hStdError=wPipe;
char command[1024];
strcpy(command,csExecute.GetBuffer(csExecute.GetLength()));
//Create the process here.
CreateProcess(0,command,0,0,TRUE,NORMAL_PRIORITY_CLASS|CREATE_NO_WINDOW,0,0,&sInfo,&pInfo);
CloseHandle(wPipe);
//now read the output pipe here.
char buf[100];
DWORD reDword;
CString m_csOutput,csTemp;
BOOL res;
do
{
res=::ReadFile(rPipe,buf,100,&reDword,0);
csTemp=buf;
m_csOutput+=csTemp.Left(reDword);
}while(res);
CloseHandle( pInfo.hProcess );
CloseHandle( pInfo.hThread );
return m_csOutput;
}
Creating a Child Process with Redirected Input and Output
You are going overkill.
For a command line app, the system command will do what you are looking for.
int status = system("MyEXEFile.exe Arg1 Arg2");
I am learning D and trying to split strings:
import std.stdio;
import std.string;
auto file = File(path, "r");
foreach (line; file.byLine) {
string[] parts = split(line);
This fails to compile with:
Error: cannot implicitly convert expression (split(line)) of type char[][] to string[]
This works:
auto file = File(path, "r");
foreach (line; file.byLine) {
char[][] parts = split(line);
But why do I have to use a char[][]? As far as I understand the documentation, it says that split returns a string[], which I would prefer.
Use split(line.idup);
split is a template function, the return type depends on its argument. file.byLine.front returns a char[] which is also reused for performance reasons. So if you need the parts after the current loop iteration you have to do a dup or idup, whatever you need.
You can use std.stdio.lines. Depending on how you type the variable of your foreach loop, it will allocate a new buffer for every iteration or reuse the old. This way you can save the .dup/.idup.
However what type to choose depends on your use case (i.e. how long do you need the data).
foreach(string line; lines(file)) { // new string every iteration }
foreach(char[] line; lines(file)) { // reuse buffer }
Using ubyte instead of char will disable the utf8 validation.
Hi i have been working with tcl scripting for almost a year and now understand almost basics of it completely. But today i just came across nested procedures which is kind of strange as i did not get the use of it.
Anyways, i read about nested proc here but did not get the clear idea as of why do we need it.
The article says that since proc's are global in a namespace so to create a local proc you make nested proc's.
proc parent {} {
proc child {} {
puts "Inside child proc";
}
...
}
Now one usage i can think of is like
proc parent {} {
proc child {intVal} {
puts "intVal is $intVal";
}
puts "[::child 10]";
... #some processing
puts "[::child 20]";
... #some processing
puts "[::child 30]";
... #some processing
puts "[::child 40]";
... #some processing
puts "[::child 50]";
... #some processing
}
So now the child proc is local to the parent proc and could be used only inside parent proc. And also as i understand it is useful when you want to do same processing at multiple places inside that parent proc.
Now my confusion is that Is this the only use of nested proc or is there anything else that i did not understand???. I mean the nested proc just seems like a kind of private proc.
So please shed some light on it and help me understand the use of nested proc's.
Tcl doesn't have nested procedures. You can call proc inside a procedure definition, but that's just creating a normal procedure (the namespace used for resolution of the name of the procedure to create will be the current namespace of the caller, as reported by namespace current).
Why would you put proc inside proc? Well, the real reason for doing so is when you want to have the outer command act as a factory, to create the command when it is called. Sometimes the name of the command to create will be supplied by the caller, and sometimes it will be internally generated (in the latter case, it is normal to return the name of the created command). The other case that comes up is where the outer command is some sort of proxy for the (real) inner one, allowing the postponing of the creation of the real command because it is expensive in some fashion; if that's the case, the inner procedure will tend to actually be created with the same name as the outer one, and it will replace it (though not the executing stack frame; Tcl's careful about that because that would be crazy otherwise).
In the case where you really need an “inner procedure” it's actually better to use a lambda term that you can apply instead. That's because it is a genuine value that can be stored in a local variable and which will automatically go away when the outer procedure terminates (or if you explicitly unset the variable or replace its contents). This inner code won't have access to the outer code's variables except via upvar; if you want to return the value while still binding variables, you should use a command prefix and include a bit of extra trickery to bind the variables as pre-supplied arguments:
proc multipliers {from to} {
set result {}
for {set i $from} {$i <= $to} {incr i} {
lappend result [list apply {{i n} {
return [expr {$i * $n}]
}} $i]
}
return $result
}
set mults [multipliers 1 5]
foreach m $mults {
puts [{*}$m 2.5]
}
# Prints (one per line): 2.5 5.0 7.5 10.0 12.5
Using an inner proc to simulate apply
Note that the apply command can actually be simulated by an inner procedure. This was a technique used in Tcl 8.4 and before:
# Omitting error handling...
proc apply {lambdaTerm args} {
foreach {arguments body namespace} $lambdaTerm break
set cmd ${namespace}::___applyLambad
proc $cmd $arguments $body
set result [uplevel 1 [linsert 0 $args $cmd]]; # 8.4 syntax for safe expansion!
rename $cmd ""
return $result
}
This was somewhat error-prone and very slow as it would recompile on each invocation; we don't do that any more!
Tcl does not have nested procs. From the proc man page:
Normally, name is unqualified (does not include the names of any containing namespaces), and the new procedure is created in the current namespace.
(emphasis mine)
To demonstrate:
% namespace eval foo {
proc parent {} {
proc child {} {
puts "the child"
}
puts "the parent, which holds [child]"
}
}
% foo::parent
the child
the parent, which holds
% foo::child
the child
We can still call the "inner" proc directly -- it's not local to the enclosing proc.
One item you missed in the discussion in that wiki page is that to make a proc truly local only to the enclosing proc, one must delete it at the end of the enclosing proc:
% namespace eval foo {
proc parent {} {
proc child {} {
puts "the child"
}
puts "the parent, which holds [child]"
# now, destroy the inner proc
rename child ""
}
}
% foo::parent
the child
the parent, which holds
% foo::child
invalid command name "foo::child"
As to the use of a local proc, I'd agree with you that it's beneficial to encapsulate repetive tasks that are only useful in the current proc. I wouldn't get too hung up on that though: clear documentation or code conventions will do just as well.
I've registered LUA api function by using:
lua_register( luaState, "someFunc", aaa::someFunc);
this function has to load a string from the someFunc's argument.
I am doing it with:
int aaa::someFunc( lua_State* state ) {
const char* _arg = ( const char* )lua_tostring( state, -1 );
// ...
return 0;
}
it works ok, until I put to someFunc() some symbols of my language like: ą, ł, ź etc (it's 'a', 'l', 'z' written holding ALT key). For these symbols qDebug( "%s", _arg )* gives me only "?" for them all. How to recognize these values in my program?
For example when I use in my script sendFunc( "Aaś" ) the printed _arg is "Aa?".
*qDebug is from Qt library, it works the same as printf() but outputs to debug window.
Thanks.
QT uses Unicode strings. I expect that the string returned from Lua is in some other codepage. You'll need to convert it to Unicode to use with qDebug.
To see what's really in the string (in terms of hex values), breakpoint your code before calling qDebug.