Quick Start
The C++/Tcl library allows to easily integrate these two languages.It is easy to both extend the Tcl interpreter and to embed the Tcl interpreter in a regular C++ code.
Hello World (extending Tcl)
Let's take the following C++ file:// example1.cc
#include "cpptcl.h"
#include <iostream>
using namespace std;
void hello() {
cout << "Hello C++/Tcl!" << endl;
}
CPPTCL_MODULE(Mymodule, i) {
i.def("hello", hello);
}
After compiling (let's suppose that the resulting shared library is named
mymodule.so
), we can do this:$ tclsh
% load ./mymodule.so
% hello
Hello C++/Tcl!
% for {set i 0} {$i != 4} {incr i} { hello }
Hello C++/Tcl!
Hello C++/Tcl!
Hello C++/Tcl!
Hello C++/Tcl!
%
In other words, the Tcl interpreter was extended with the loadable module (which is a shared library) that provides the definition of new command.
// example2.cc
#include "cpptcl.h"
#include <iostream>
#include <string>
using namespace std;
using namespace Tcl;
void hello() {
cout << "Hello C++/Tcl!" << endl;
}
int main() {
interpreter i;
i.def("hello", hello);
string script = "for {set i 0} {$i != 4} {incr i} { hello }";
i.eval(script);
}
After compiling, it gives the following result:
$ ./example2
Hello C++/Tcl!
Hello C++/Tcl!
Hello C++/Tcl!
Hello C++/Tcl!
$
In other words, the Tcl interpreter exists in a C++ application as a regular object.
It is possible to define new commands in this interpreter and execute arbitrary Tcl scripts in it, so that C++ and Tcl communicate with each other.