URN Logo
UNIX Resources » Linux » China Linux Forum » Python 编 程 » 10 » 请教一个用boost.python在应用程序中嵌入python问题?
announcement 声明: 本页内容为中国Linux论坛的内容镜像,文章的版权以及其他所有的相关权利属于中国Linux论坛和相应文章的作者,如果转载,请注明文章来源及相关版权信息。
Resources
China Linux Forum(finished)
Linux Forum(finished)
FreeBSD China(finished)
linuxforum.net
  业界新闻与评论
  自由软件杂谈
  IT 人生
  Linux软件快递
  翻译作坊
  Linux图书与评论
  GNU Emacs/XEmacs
  Linux 中文环境和中文化
  Linux桌面与办公软件
  Linux 多媒体与娱乐版
  自由之窗Mozilla
  笔记本电脑上的Linux
  Gentoo
  Debian 一族
  网络管理技术
  Linux 安装与入门
  WEB服务器和FTP服务器
  域名服务器和邮件服务器
  Linux防火墙和代理服务器应用
  文件及打印服务器
  技术培训与认证
  Linux内核技术
  Linux 嵌入技术
  Linux设备驱动程序
  Linux 集群技术
  LINUX平台数据库
  系统和网络安全
  CPU 与 编译器
  系统计算研究所专栏
  Linux下的GUI软件开发
  C/C++编程版
  PHP 技 术
  Java&jsp技术
  Shell编程技术
  Perl 编 程
  Python 编 程
  XML/Web Service 技术
  永远的Unix
  FreeBSD世界
   
请教一个用boost.python在应用程序中嵌入python问题?
Author: blast2001    Posted: 2005-04-20 17:42    Length: 3,111 byte(s)
[Original] [Print] [Top]
我想在自己的C++(Linux下开发)程序里嵌入Python,让它可以使用Python程序作为脚本。 Python脚本可以读/写C++程序里面的变量、使用C++里面的类和函数.
现在遇到一个问题:
如何把C++的一个自定义的类对象实例传递给python, 并在脚本中访问(简单对象的传递已基本搞定)。

代码:
#include <boost/python.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/python/class.hpp>

#include <boost/python/module.hpp>

#include <boost/python/def.hpp>
#include <iostream>
#include <string>
#include <list>
#include <map>

using namespace std;
namespace python = boost::python;

class Base
{
public:
Base(int x)
{
i = x;
}
virtual ~Base() {};
virtual void hello()
{

};
private:
int i;
};

BOOST_PYTHON_MODULE(embedded_hello)
{
using namespace boost::python;
class_<Base>("Base", init<int>())
// Add a regular member function.
.def("hello", &Base::hello)
;
}

int main()
{
// Register the module with the interpreter
if (PyImport_AppendInittab("embedded_hello", initembedded_hello) == -1)
throw std::runtime_error("Failed to add embedded_hello to the interpreter's "
"builtin modules");

// Initialize the interpreter
Py_Initialize();

// Retrieve the main module
python::object main_module((
python::handle<>(python::borrowed(PyImport_AddModule("__main__")))));

// Retrieve the main module's namespace
python::object main_namespace((main_module.attr("__dict__")));

Base * pBase = new Base(2000);
main_namespace["retValue"] = 5; // it is ok here
PyObject *arglist = Py_BuildValue( "(o)", pBase );;
main_namespace["AppBase"] = arglist; //here abort

python::handle<> result(
PyRun_String(
"from embedded_hello import * "
"print retValue "
"print AppBase.i "
"hi = Base(500) "
"hi2 = Base(1000) ",
Py_file_input, main_namespace.ptr(), main_namespace.ptr())
);
// Result is not needed
result.reset();

Py_Finalize();
}

请教一下该怎么显式传递对象? 多谢 !
[Original] [Print] [Top]
« Previous thread
freeeze的问题
Python 编 程
10
Next thread »
怎么取得HTTP连接时的状态码?
     

Copyright © 2007 UNIX Resources Network, All Rights Reserved.      About URN | Privacy & Legal | Help | Contact us
备案序号: 京ICP备05006143    webmaster: webmaster@unixresources.net
This page created on 2008-07-17 04:11:14, cost 0.06827187538147 ms.