gpt4 book ai didi

c++ - 如何使用 Boost::Python 打印到 Python 终端

转载 作者:行者123 更新时间:2023-11-28 05:47:03 25 4
gpt4 key购买 nike

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

我找到了以下网站: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()

我通过让它返回一些东西来检查函数是否被调用并且它有效,但仍然没有打印任何内容。

谢谢你的帮助

最佳答案

这个 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!

关于c++ - 如何使用 Boost::Python 打印到 Python 终端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36020136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com