⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 test.cpp

📁 这是一个tcl和c集成的例子
💻 CPP
字号:
//demo.cpp: 演示Tcl_CreateCommand,Tcl_LinkVar用法的小例子
//1。在C程序中调用Tcl脚本,在Tcl脚本中调用c函数。
//2。将c和tcl变量连接一起,当在c程序中改变c变量时,与之连接的tcl变量也发生改变,
//	 同样,在tcl脚本中改变tcl变量时,与之连接的c变量也发生相同的改变。
//URL: http://www.online.sdu.edu.cn/home/sduhome/wesley/
//E-Mail:wesley546@163.com


/*程序中使用的tcl文件:test.tcl

global c_min
global c_max
global c_statusString

button .b -text EXIT -command exit -width 8;
button .c -text $c_min -width 8 -command {set c_min [expr $c_min + 1.0 ];.c configure -text $c_min;c_infoprint}
button .d -text $c_max -width 8 -command {set c_max [expr $c_max + 1.0 ];.d configure -text $c_max;c_infoprint}
button .e -text text1 -width 8 -command {set c_statusString text1;c_infoprint}
button .f -text text2 -width 8 -command {set c_statusString text2;c_infoprint}
button .g -text text3 -width 8 -command {set c_statusString text3;c_infoprint}

pack  .c .d .e .f .g .b

*/

#include <stdio.h>
#include <stdlib.h>
#include "tcl.h"
#include "tk.h"

//Global variables
double min=0.0,max=10.0;
char *statusString = Tcl_Alloc(30 * sizeof(char));


int infoprint(ClientData clientData,Tcl_Interp *interp,int argc, CONST char *argv[]);

int main(int argc, char** argv) 
{

	Tcl_Interp *interp;//定义解释器
	interp = NULL;
	int error;
	const char *trace;
	strcpy (statusString, "Start string");

	Tcl_FindExecutable(argv[0]);
	interp = Tcl_CreateInterp();//创建该解释器
	if (NULL == interp)
	{
		printf("fail to create interp!\n");
		exit(1);
	} 
	if (TCL_ERROR == Tcl_Init(interp))
	{
		printf("fail to initialize tcl!\n");
		exit(1);
	} 
	if (TCL_ERROR == Tk_Init(interp))
	{
		printf("fail to initialize tk!\n");
		exit(1);
	}
	
	Tcl_CreateCommand(interp, "c_infoprint", infoprint,
		(ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
	
	Tcl_LinkVar(interp,"c_min",(char*)&min,TCL_LINK_DOUBLE);
	Tcl_LinkVar(interp,"c_max",(char*)&max,TCL_LINK_DOUBLE);
	Tcl_LinkVar(interp, "c_statusString", (char *)&statusString,TCL_LINK_STRING);
	
	printf("调用tcl脚本前,c变量的值为:\nmin = %f, max = %f, statusString = %s\n", 
		min, max,statusString);

	error = Tcl_EvalFile(interp,"test.tcl");

	
	if (error != TCL_OK) 
	{
		fprintf(stderr, "%s: %s\n", argv[1],interp->result);
		trace = Tcl_GetVar(interp, "errorInfo",TCL_GLOBAL_ONLY);
		if (trace != NULL) 
		{
			fprintf(stderr, "*** TCL TRACE ***\n");
			fprintf(stderr, "%s\n", trace);
		}
		exit(1);
	}
	else
	{
		printf("%s\n", interp->result);
	}
	
	Tk_MainLoop();
    
	Tcl_DeleteInterp(interp);
	
	return 0;
}


int infoprint(ClientData clientData,Tcl_Interp *interp,int argc, CONST char *argv[])
{
	printf("当前c变量的值为: min = %f, max = %f, statusString = %s\n", 
		min, max, statusString);
	min++;
	interp->result ="ok";
	Tcl_Eval(interp,"show");
	return 0;
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -