accessing python objects from C++

Stevek skille at ameritech.net
Wed Dec 18 00:25:50 EST 2002


I'm embedding a python interpreter that allows the user to create and
evaluate scripts that reference historical stock data.  For the most part,
things are going well.  I can embed the interpreter, populate the
dictionaries with price data (of type double), run the user's script, and
retrieve the results.



What I can't seem to figure out however is how I can populate the global
dictionary with a custom date object from within the C++ application.  The
C++ application is cycling through all the historical data day by day and
populating the dictionary with stock prices.



The stock prices can be placed in the dictionary with code similar to the
following:



PyDict_SetItemString( m_pLocalDict, "LastPrice",
PyFloat_FromDouble(value) );



Since Python provides the PyFloat_FromDouble() conversion routine, this is
pretty easy.  However, populating the dictionary with a date object doesn't
seem to be as straight foward.  I have created my own Python date class, and
would like to update it's value with a date that corrosponds to the price
data that was also placed in the dictionary.



I want to use my own date class because I'm performing some special
calculations.  How do I access and alter Python class variables from within
the C++ application?  I have a custom date class such as:







class ValDate:

    julDate = 0



    year    = 2002

    month   = 9

    day     = 30



    def __init__(self, valDate=None):



        if ValDate is None:

            self.setValDate(time.localtime(time.time()))

        else:

            self.setValDate(valDate)



            .

            .

            .



psudo code for populating dictionaries and calculating scripts:



for( int i=0; i<days; i++)

{

            PyDict_SetItemString( m_pLocalDict, "HighPrice",
PyFloat_FromDouble( stockHighPrices[i] ) );

            PyDict_SetItemString( m_pLocalDict, "LowPrice",
PyFloat_FromDouble( stockLowPrices[i] ) );



            // now I would like to do something similar to set the
corrosponding ValDate

            PyDict_SetItemString( m_pLocalDict, "CurDate",
PyObject_FromXXXX( stockDates[i] ) );



            // run a simple script such as "rslt = (HighPrice + LowPrice) /
2"

                PyRun_String( script, file_input , m_pGlobalDict,
m_pLocalDict);



            // get value of scripts output from dictionary

               PyObject* pval = PyDict_GetItemString( m_pLocalDict, "rslt");



            .

            .

            .

}





First I need to place an instance of a ValDate into the global dictionary.
Then I need to be able to change it's value from within the C++ application.



Any assistance would be much appreciated.









More information about the Python-list mailing list