Skip to content

Instantly share code, notes, and snippets.

@liwenxiang
Created September 11, 2014 16:45
c++ 调用python
g++ new.cpp -I/usr/include/python2.4 -fPIC -lpython2.4
#include <Python.h>
#include <iostream>
#include <string>
using namespace std;
bool calc(const string& filename, char* methodname, const string& expression, double& result)
{
PyObject *pyFileName = PyString_FromString(filename.c_str());
PyObject *pyMod = PyImport_Import(pyFileName); // load the module
if(pyMod) // if ok
{
// load the function
PyObject *pyFunc = PyObject_GetAttrString(pyMod, methodname);
if(pyFunc && PyCallable_Check(pyFunc))
{
PyObject *pyParams = PyTuple_New(1);
PyObject *pyValue = PyString_FromString(expression.c_str());
PyTuple_SetItem(pyParams, 0, pyValue);
// ok, call the function
pyValue = PyObject_CallObject(pyFunc, pyParams);
if(pyValue)
{
result = PyFloat_AsDouble(pyValue);
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
return false;
}
int main(int argc, char *argv[])
{
string filename = "python_code"; // file name is settled!
string inputParam = "Hello World"; // get user input!
double result = 0.0;
Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(argc, argv);
if(calc(filename, "calculate", inputParam, result))
{
printf("/nResult is : %lf/n", result);
}
Py_Finalize();
}
def calculate(expression):
try:
# result = eval(expression)
print expression
except:
print 'Eval error!'
return -1.0
return 1.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment