[C++-sig] Re: newbie: need example (call python from c++)

David Abrahams dave at boost-consulting.com
Sun Jul 4 18:55:56 CEST 2004


The following message is a courtesy copy of an article
that has been posted to gmane.comp.lib.boost.user as well.

Peter Piehler <ppiehler at yahoo.de> writes:

> Hello,
>
> I use call<void>(pyFunc,arg1,..) to call a python
> function with standard double, int etc.

Please bring Boost.Python questions to the C++-sig:
http://www.boost.org/more/mailing_lists/cplussig

> What must I do to call a function with a c++ object as
> argument?

A standard double is a c++ object.  I presume you mean an instance of
a C++ class.  Just pass it to call and make sure its class has been
wrapped.

> psydocode:
>
> class MyAnimal
> {
>        /*...*/
>        std::string __strName;
>     public:
>        MyAnimal() : __strName("Tux") {}
>        /*...*/
>        std::string getName()
>            { return __strName;}
>        void setName(const std::string &strName)
>            { __strName = strName; }
> };
>
> int main()
> {
>   /*...*/
>   MyAnimal* pTux = new Animal;
>   /*do something with pTux*/
>
>   /*use a python function with pTux*/
>   call<void>(pyFunc1, ?pTux? );

    You can pass pTux or *pTux; that will cuase *pTux to be copied
    into a Python object.  You can pass ptr(pTux) or ref(*pTux); that
    will pass a Python object that only holds *pTux by reference (no
    lifetime management)

>   /*change attributes pTux in pyFunc2*/
>   dog = call<MyAnimal>(pyFunc2, ?pTux?);
>
>   /*if it possible to call by reference?*/
>   call<void>(pyFunc3, ?pTux?);
>   pTux->getName();// return Cat

-- 
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com





More information about the Cplusplus-sig mailing list