Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3998148
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T07:29:22+00:00 2026-05-20T07:29:22+00:00

I am new to boost python. I have to first init a cpp class

  • 0

I am new to boost python. I have to first init a cpp class instance in cpp code, and then pass this cpp instance to python code, use a python class instance to invoke it(the cpp instance). I have tried the Python/C API way, but failed, so I wonder how to pass a c++ class instance to a python class.

The following is my code, changed from the boost python demo.

in main.cpp

#include <python2.6/Python.h>
#include <boost/python.hpp>
#include <iostream>

using namespace boost::python;
using namespace std;

class World
{
private:
    string name;
public:
    void set(string name)
    {
        this->name = name;
    }
    void greet()
    {
        cout << "hello, I am " << name << endl;
    }
};

typedef boost::shared_ptr< World > world_ptr;

BOOST_PYTHON_MODULE(hello)
{
    class_<World>("World")
    .def("greet", &World::greet)
    .def("set", &World::set)
    ;

    register_ptr_to_python<world_ptr>();
};

int main()
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");

    world_ptr worldObjectPtr (new World);
    worldObjectPtr->set("C++!");

    try
    {
        inithello();
        PyObject* pModule =PyImport_ImportModule("python");
        PyObject* pDict = PyModule_GetDict(pModule);
        PyObject* pClassHelloPython = PyDict_GetItemString(pDict, "Person");
        PyObject* pInstanceHelloPython = PyInstance_New(pClassHelloPython, NULL, NULL);

        PyObject_CallMethod(pInstanceHelloPython, "sayHi", NULL);
        worldObjectPtr->greet();
        PyObject_CallMethod(pInstanceHelloPython, "greetReset", "O", worldObjectPtr);
        worldObjectPtr->greet();
    }
    catch (error_already_set)
    {
        PyErr_Print();
    }

    Py_Finalize();

    return 0;
}

in python.py

class Person:
    def sayHi(self):
        print 'hello from python'

    def greetReset(self, instance):
        instance.set('Python')

In the above code, I want to pass the worldObjectPtr to the pInstanceHelloPython, thus, pInstanceHelloPython can set the worldObjectPtr->name to Python. But I just don’t know how to do it. Thank you for your patience in advance!!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T07:29:23+00:00Added an answer on May 20, 2026 at 7:29 am

    Pass the object pointer via boost::python::ptr to python. This will prevent the python interpreter from makeing a copy:

    #include <boost/python.hpp>
    #include <string>
    #include <iostream>
    
    using namespace boost::python;
    using namespace std;
    
    class World
    {
    private:
        string name;
    public:
        void set(string name) {
            this->name = name;
        }
        void greet() {
            cout << "hello, I am " << name << endl;
        }
    };
    
    typedef boost::shared_ptr< World > world_ptr;
    
    BOOST_PYTHON_MODULE(hello)
    {
        class_<World>("World")
            .def("greet", &World::greet)
            .def("set", &World::set)
        ;
    };
    
    int main(int argc, char **argv)
    {
        Py_Initialize();
        try {
            PyRun_SimpleString(
                "class Person:\n"
                "    def sayHi(self):\n"
                "        print 'hello from python'\n"
                "    def greetReset(self, instance):\n"
                "        instance.set('Python')\n"
              );
    
            world_ptr worldObjectPtr (new World);
            worldObjectPtr->set("C++!");
    
            inithello();
            object o_main 
                = object(handle<>(borrowed(PyImport_AddModule("__main__"))));
            object o_person_type = o_main.attr("Person");
            object o_person = o_person_type();
            object o_func1 = o_person.attr("sayHi");
            o_func1();
            object o_func2 = o_person.attr("greetReset");
            o_func2(boost::python::ptr(worldObjectPtr.get()));
            worldObjectPtr->greet();
        }
        catch (error_already_set) {
            PyErr_Print();
        }
    
        Py_Finalize();
    
        return 0;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

First off, a big thanks to the people behind the new boost::geometry library! This
Brief version of my question: This code crashes the compiler. pThread[0] = new boost::thread(
I have a snippet of code like this: std::list<boost::shared_ptr<Point> > left, right; // ...
I would like to compile parallel.cu and python_wrapper.cpp where python_wrapper.cpp use Boost.python to expose
I'm new in using boost and have a problem. I need shared_mutex function in
New to PHP and MySQL, have heard amazing things about this website from Leo
I have a library which creates objects (instances of class A) and pass them
I've been trying to extend Python with C++ using Boost in Windows 7. This
I am new to C++/Python mixed language programming and do not have much idea
Class member functions in Python have to explicitly declare a self parameter which represents

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.