网上找来的看下。。
附1 text.txt
this is test text in text.txt.
附2 mymod.py
import string
message = ''original string''
message =message+message
msg_error=""
try:
text_file = open("text.txt", "r")
whole_thing = text_file.read()
print whole_thing
text_file.close()
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
def transform(input):
#input = string.replace(input, ''life'', ''Python'')
return string.upper(input)
def change_msg(nul):
global message #如果没有此行,message是函数里头的局部变量
message=''string changed''
return message
def r_file(nul):
return whole_thing
def get_msg(nul):
return message
附3 simplepy.h
using std::string;
class CSimplepy // : private noncopyable
{
public:
///constructor
CSimplepy()
{
Py_Initialize();
pstr=NULL, pmod=NULL, pdict=NULL;
pfunc=NULL, pargs=NULL;
}
virtual ~CSimplepy()
{
Py_Finalize();
}
bool ImportModule(const char* mod_name)
{
try{
pmod = PyImport_ImportModule(const_cast(mod_name));
if(pmod==NULL)
return false;
pdict = PyModule_GetDict(pmod);
}
catch(...)
{
return false;
}
if(pmod!=NULL && pdict!=NULL)
return true;
else
return false;
}
int Run_SimpleString(const char* str)
{
return PyRun_SimpleString(const_cast(str) );
}
string Run_String(const char* str)
{
char *cstr;
pstr = PyRun_String(str, Py_eval_input, pdict, pdict);
if(pstr==NULL)
throw ("when Run_String, there is an exception was raised by Python environment.");
PyArg_Parse(pstr, "s", &cstr);
return string(cstr);
}
string CallObject(const char* func_name, const char* parameter)
{
pfunc=NULL;
pfunc = PyObject_GetAttrString(pmod, const_cast(func_name));
if(pfunc==NULL)
throw (string("do not found in Python module for: ")
+func_name).c_str();
char* cstr;
pargs = Py_BuildValue("(s)", const_cast(parameter));
pstr = PyEval_CallObject(pfunc, pargs);
if(pstr==NULL)
throw ("when PyEval_CallObject, there is an exception was raised by Python environment");
PyArg_Parse(pstr, "s", &cstr);
return string(cstr);
}
protected:
PyObject *pstr, *pmod, *pdict;
PyObject *pfunc, *pargs;
};