如何向python的脚本传递一个类作为参数。

mmosquito 2005-04-26 04:32:51
使用到了boost.python

主程序如下:

using namespace boost::python;

struct World
{
void set(std::string msg) { this->msg = msg; }
std::string greet() { return msg; }
std::string msg;
};

BOOST_PYTHON_MODULE(hello)
{
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set)
;
}

int _tmain(int argc, _TCHAR* argv[])
{
Py_Initialize();

if (!Py_IsInitialized())
return -1;

inithello();
}

PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");

PyObject* pName,*pModule,*pDict,*pFunc,*pArgs;

pName = PyString_FromString("pytest");
pModule = PyImport_Import(pName);
if (!pModule)
return -1;

pDict = PyModule_GetDict(pModule);
if (!pDict)
return -1;

pFunc = PyDict_GetItemString(pDict,"add");
if (!pFunc || !PyCallable_Check(pFunc))
return -1;

World w;
w.set("hi from main!");

pArgs = PyTuple_New(3);
PyTuple_SetItem(pArgs,0,Py_BuildValue("i",3));
PyTuple_SetItem(pArgs,1,Py_BuildValue("i",4));
PyTuple_SetItem(pArgs,2,Py_BuildValue("O",&w));

try
{
PyObject_CallObject(pFunc,pArgs);
}
catch(error_already_set)
{
// handle the exception in some way
}

Py_DECREF(pName);
Py_DECREF(pArgs);
Py_DECREF(pModule);

Py_Finalize();
getchar();

return 0;
}

脚本如下:

import hello
from hello import *
def add(a,b,t):
print "a + b = " + str(a+b)
w = hello.World()
w.set("hi from script!")
print w.greet()
print t.greet()
return

结果运行到print t.greet()就异常了

怎么样才能把一个类作为参数传递到python中去阿?
...全文
421 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
airless 2005-06-05
  • 打赏
  • 举报
回复
不知道我的理解是否正确,如果大大你是想把一个C类传递到Python中,让Python能认识你这类的话,你这样是不行的,”PyTuple_SetItem(pArgs,2,Py_BuildValue("O",&w));“ 这里,Python环境不识你的World类型,这需要你把这个结构弄成一个PyTypeObject类型的对象(如何搞,可以参考Python源码中的对象使用,建议参考_socket.socket对象的代码),还有一点比较重要,在从C向Python的过程中,所有C类和结构对于Python来说都是一种数据类型,这在C中没有太大感觉,在Python中比较明显,希望有帮到楼主。
fibbery 2005-04-26
  • 打赏
  • 举报
回复
不知道你想怎么传,如果想从命令行传进去,只能变通的实现。比如说,传一个配置文件名,然后分析配置文件初始化程序中使用的类。
mmosquito 2005-04-26
  • 打赏
  • 举报
回复
初学python,真的山穷水尽了,大侠们请不吝赐教。

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧