如何使用Boost::P ython打印到Python终端

How to print to Python terminal with Boost::Python

本文关键字:Python 终端 打印 何使用 Boost ython      更新时间:2023-10-16

我想从我用C++编写的库中用python进行相当于打印。我正在使用Boost 1.60.0和Python 2.7。

我找到了以下网站:Mantid和WikiBooks。据我所知,这段代码应该可以工作,但没有打印任何内容。

CPP 文件

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

py 文件

import PythonIntegration
PythonIntegration.greet()

我检查了该函数是否通过使其返回某些内容来调用并且它可以工作,但仍然没有打印任何内容。

谢谢你的帮助

这个hello world示例似乎完全符合您的要求:https://en.wikibooks.org/wiki/Python_Programming/Extending_with_C%2B%2B

基本上。。。

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);
}

现在,在 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"])
    ])

现在你可以这样做:

python setup.py build

然后在python命令提示符下:

>>> import hello
>>> hello.say_hello("World")
Hello World!