Question

I want to declare a pointer in c++:

class MyAgent : public Agent
{
private:
    int x,y;
    int* xPtr;
    int *yPtr;
    void add();
public:
    MyAgent(); // Declaration of constructor
};

MyAgent::MyAgent() : Agent(PT_UDP)
{
    xPtr= &x;
    yPtr= &y;
    bind("x_otcl", &x);
    bind("y_otcl", &y);

} 
void MyAgent::add()
{
    Tcl& tcl = Tcl::instance();
    tcl.eval("puts \"From add() \"");
    printf("\nx=%d and y = %d\nx+y = %d\n", x,y,x+y);
    printf("xPtr=%d\n",*xPtr);
    printf("yPtr=%d\n",*yPtr);
}

What is the difference between xPtr and yPtr? Is xPtr a pointer? Does the compiler ignore the space? From the results, I figured that both of them are pointers but I'm not sure. I always use the second one (yPtr) for declaration of pointers.

Also please tell me how to bind pointers between c++ and otcl.

Was it helpful?

Solution

Both xPtr and yPtr are pointers to integer. Yes, compilers ignore the space.

To bind an oTcl variable (x and y) with C++ variables (*xPtr and *yPtr), use the following code.

Tcl& tcl = Tcl::instance();
tcl.eval("set variable_in_tcl");
variable_in_c++ = atoi(tcl.result());

As, I have understand, you are calling the add() function which will take the variables xPtr and yPtr value from oTcl script and print the value of variable. So, your code will look as follows:

class MyAgent : public Agent
{
private:
    // Use x and y in tcl script

    int* xPtr;

    int *yPtr;

    void add();

public:

    MyAgent(); // Declaration of constructor
};

MyAgent::MyAgent() : Agent(PT_UDP)
{
    Tcl& tcl = Tcl::instance();
    tcl.eval("set x");
    *xPtr = atoi(tcl.result());
    tcl.eval("set y");
    *yPtr = atoi(tcl.result());
}

void MyAgent::add()
{
    printf("\nx=%d and y = %d\nx+y = %d\n", *xPtr,*yPtr,*xPtr+*yPtr);

    printf("xPtr=%d\n",*xPtr);

    printf("yPtr=%d\n",*yPtr);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top