How to pass a arg of object to python's script in a c++ program?

Z

zghelp

/*I am sorry the prev post is a mistake...*/

//the c++ code

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

//the python's script

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


but the exception occur when run to "print t.greet()"

How can I solve it?
 
M

Mike Rovner

Couple notes:
- boost.python issues better discuss in comp.lang.python.c++ group;
- debug your extension from python first, then embed it
- don't call PyFinalize()
but the exception occur when run to "print t.greet()"

How can I solve it?

Providing exception text will be helpful.

Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top