2016-03-15 43 views
0

我想在C++中編寫的庫中執行相當於python中的打印操作。我正在使用Boost 1.60.0和Python 2.7。如何使用Boost :: Python打印Python終端:: Python

我發現以下網站:MantidWikiBooks。從我所瞭解的代碼應該工作,但沒有打印。

CPP文件

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

PY文件

import PythonIntegration 
PythonIntegration.greet() 

我檢查,如果該功能是通過使其返回一種叫和它的作品,但還是被打印什麼。

謝謝您的幫助

回答

1

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

現在,在設置.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 

然後在蟒蛇命令提示符:

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

沒錯。你的例子與這裏的hello world例子非常相似... http://www.boost.org/doc/libs/1_55_0/libs/python/doc/tutorial/doc/html/index.html – LawfulEvil

+0

你並不是真的關心它調用你的函數(它是),你更擔心/擔心重定向C++的stdout回到python並從python打印它? – LawfulEvil

+0

是的,沒錯! – Heckel