在尝试了很多并搜索 Web 选项来编译和加载 dll 之后,我无法为 tcl 创建 dll。你能解释一下如何做到这一点。
最佳答案
好的,这是一个简单的例子。此代码编译并适用于 Tcl8.5 和 VS2008。首先,我创建了一个名为 BasicTclExtn 的 WIN32 dll 项目,用于导出符号。
// BasicTclExtn.h
#ifdef BASICTCLEXTN_EXPORTS
#define BASICTCLEXTN_API __declspec(dllexport)
#else
#define BASICTCLEXTN_API __declspec(dllimport)
#endif
int BasicExtnCmd(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) ;
extern "C" {
BASICTCLEXTN_API int Basictclextn_Init(Tcl_Interp *interp) ;
}
然后是 .cpp 文件
// BasicTclExtn.cpp : Defines the exported functions for the DLL application.
#include "stdafx.h"
#include "BasicTclExtn.h"
int
BasicExtnCmd(ClientData data,
Tcl_Interp *interp,
int objc,
Tcl_Obj *CONST objv[])
{
// Check the number of arguments
if (objc != 3) {
Tcl_WrongNumArgs(interp, 1, objv, "arg arg");
return TCL_ERROR;
}
long v1, v2, result ;
if ( Tcl_GetLongFromObj(interp, objv[1], &v1) != TCL_OK)
return TCL_ERROR ;
if ( Tcl_GetLongFromObj(interp, objv[2], &v2) != TCL_OK)
return TCL_ERROR ;
result = v1 + v2 ;
Tcl_SetObjResult(interp, Tcl_NewIntObj(result)) ;
return TCL_OK ;
}
// Note the casing on the _Init function name
BASICTCLEXTN_API int Basictclextn_Init(Tcl_Interp *interp)
{
// Link with the stubs library to make the extension as portable as possible
if (Tcl_InitStubs(interp, "8.1", 0) == NULL) {
return TCL_ERROR;
}
// Declare which package and version is provided by this C code
if ( Tcl_PkgProvide(interp, "BasicTclExtn", "1.0") != TCL_OK ) {
return TCL_ERROR ;
}
// Create a command
Tcl_CreateObjCommand(interp, "BasicExtnCmd", BasicExtnCmd, (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL);
return TCL_OK ;
}
您需要在 stdafx.h 中 #include tcl.h。
此示例使用 Tcl stub 工具,有关更多信息,请参阅有关 Tcl_InitStubs 函数的文档;使用 stub 时,您只需要链接到 tclstub85.lib。要使代码正确链接,您需要执行以下操作:
USE_TCL_STUBS
符号,我通常在 Properties-> C/C++ -> Preprocessor -> Preprocessor Definitions 中这样做。您可能还会发现,在此之后您需要定义 <DLLNAME>_EXPORTS
(在我的示例中为 BASICTCLEXTN_EXPORTS
),我不确定为什么会发生这种情况。 所有这些 .lib、.dll 和 .h 文件应该很容易在您的 Tcl 安装中找到。您还需要确保在运行时可以找到相关的 tclstub85.dll 和 tcl85.dll,确保 Tcl 的 bin 目录在 PATH 上应该可以解决这个问题。因此,您应该能够从 Tcl 执行以下操作:
C:\Projects\BasicTclExtn\Debug>tclsh
% load BasicTclExtn.dll
% BasicExtnCmd 1 2
3
% BasicExtnCmd 1 2.p
expected integer but got "2.p"
% BasicExtnCmd 1 2
3
% BasicExtnCmd 1
wrong # args: should be "BasicExtnCmd arg arg"
% BasicExtnCmd 1 3
4
% exit
这是 Tcl 扩展的最简单形式,您可以添加对
Tcl_CreateObjCommand()
的额外调用以将更多命令添加到此扩展中。 Tcl 提供了一些工具来帮助处理传递给命令的命令行参数。示例代码使用了 Tcl_WrongNumArgs()
,但您还应该查看 Tcl_GetIndexFromObj()
函数。我还建议您获取 Brent Welch 编写的 Practical Programming in Tcl 和 Tk 拷贝。你可以在这里阅读一些示例章节 http://www.beedub.com/book/ ,第三版中关于 Tcl 的 C 编程的章节会对你有很大帮助。
关于c++ - 如何在tcl中编译可加载的dll,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1392112/