0

I would like to do the equivalent of a print in python from a library I wrote in C++. I am using Boost 1.60.0 and Python 2.7.

I found the following sites :Mantid and WikiBooks. From what I understood this code should work, but nothing is printed.

cpp file

void greet()
{
    std::cout<<"test_01\n";
    std::cout<<"test_02"<<std::endl;
    printf("test_03");
}
BOOST_PYTHON_MODULE(PythonIntegration)
{
    def("greet", greet);
}

py file

import PythonIntegration
PythonIntegration.greet()

I checked if the function was called by making it return something and it works, but still nothing is printed.

Thank you for your help

1 Answer 1

2

This hello world example seems to do exactly what you want : https://en.wikibooks.org/wiki/Python_Programming/Extending_with_C%2B%2B

Basically...

C++

#include <iostream>

using namespace std;

void say_hello(const char* name) {
    cout << "Hello " <<  name << "!\n";
}

#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
using namespace boost::python;

BOOST_PYTHON_MODULE(hello)
{
    def("say_hello", say_hello);
}

Now, in setup.py

#!/usr/bin/env python

from distutils.core import setup
from distutils.extension import Extension

setup(name="PackageName",
    ext_modules=[
        Extension("hello", ["hellomodule.cpp"],
        libraries = ["boost_python"])
    ])

Now you can do this :

python setup.py build

Then at the python command prompt :

>>> import hello
>>> hello.say_hello("World")
Hello World!
Sign up to request clarification or add additional context in comments.

4 Comments

Quite right. Your example is very similar to the hello world example here... boost.org/doc/libs/1_55_0/libs/python/doc/tutorial/doc/html/…
You are not really concerned about it calling your function(which it is), you are more worried/concerned about redirecting c++'s stdout back into python and printing it from python?
See edits to my answer. Sorry about that first answer.
I have seen this example but I don't know what to do with the setup.py. I'll look into it. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.