Swig(Tcl):我可以在执行我的 C++ 程序时调用 Swig 函数吗?

Swig(Tcl): Can I call Swig function while executing my c++ program?

我有一个带有 Tcl 解释器的 c++ 程序。 我包装我的函数并手动将它们添加到 Tcl 解释器中。 是否可以通过 Swig 自动包装和添加它们?

这里是简化代码:

#include <stdio.h>
#include <tcl.h>

class SystemData {              // I have a class which link to all the data and function
public:
    void print(){
        printf("Hello!\n");
    };
};
                                // I wrap the functions manually. But I'm tired to maintain them.
int Hello( ClientData clientData, Tcl_Interp *interp, int argc, const char **argv ) {
   SystemData* system = (SystemData*) clientData;
   system->print();
}

int main (int argc, char *argv[]) {
    Tcl_Interp *interp = Tcl_CreateInterp();;
    SystemData* system = new SystemData; 
    Tcl_CreateCommand( interp, "hello", Hello, (ClientData)system, (Tcl_CmdDeleteProc *)NULL );

    Tcl_Eval(interp, "hello");  // I have a Tcl interpreter so that I can call any function in any time

    Tcl_DeleteInterp(interp);
}

我尝试通过 Swig 将 SystemData 导出到 Tcl:

// swig.cc
#include <stdio.h>
#include <tcl.h>

class SystemData {
public:
    void print(){
        printf("Hello!\n");
    };
};

SystemData* systemData;
int main (int argc, char *argv[]) {
    Tcl_Interp *interp = Tcl_CreateInterp();;
    systemData = new SystemData; 


    Tcl_Eval(interp, "load ./swig.so swig");
    Tcl_Eval(interp, "puts $systemData");

    Tcl_DeleteInterp(interp);
}

我的 Swig 界面:

/* swig.i */
 %module swig
 %{
 /* Put header files here or function declarations like below */
class SystemData;
extern SystemData* systemData;
 %}

extern SystemData* systemData;

编译命令:

swig -tcl swig.i
g++ -fpic -c swig.cc swig_wrap.c -I/usr/local/include
g++ -shared swig.o swig_wrap.o -o swig.so

但是puts $systemData的结果是

NULL

我也试过不加载swig.so 然而, puts $systemData 的结果是

can't read "systemData": no such variable

有人有想法吗?

问题出在编译命令中。我的最终命令是:

swig -c++ -tcl swig.i
g++ -fpic -c swig.cc swig_wrap.cxx 
g++ -shared swig.o swig_wrap.o -o swig.so
g++ swig.o swig_wrap.o -o swig.out -g -I/usr/local/include -L/usr/local/lib -ltcl8.5
setenv LD_LIBRARY_PATH /usr/local/lib:/usr/local/lib
./swig.out

以上命令的输出为:

swig.i:22: Warning(454): Setting a pointer/reference variable may leak memory.
_906e600000000000_p_SystemData