Calling the C API from Python and Python program from same C API -bidirectional

  • Thread starter Praveen, Tayal (IE10)
  • Start date
P

Praveen, Tayal (IE10)

Hi Guys,

I am having problems in the following C API program where myOtim_system is
callable from python function. The module is listed below -

static PyObject *
myOptim_system(PyObject *self, PyObject *args)
{
const char *command;
double u0, v0, u1, v1, u2, v2, u3, v3;
int sts;

/* variables */
PyObject *pstr, *pmod, *pdict, *pfunc, *pargs;
char * cstr;
char *dummy = "Test";
char *x = "x = ";


if (!PyArg_ParseTuple(args, "s", &command))
return NULL;

/* convert them to the doubles */
sscanf(command, "%lf %lf %lf %lf %lf %lf %lf %lf", &u0, &v0,
&u1, &v1, &u2, &v2, &u3, &v3);

sts = (int) (u0+v0+u1+v1+u2+v2+u3+v3);

/* trying to call the python program from C */
/*
The module name is test2_module and the function name is
cv_calc_func
- get test2_module.cv_calc_func
*/
pmod = PyImport_ImportModule("test2_module");
pdict = PyModule_GetDict(pmod);

/* convert to the PyObject */
pfunc = PyObject_GetAttrString(pmod, "cv_calc_func");
pargs = Py_BuildValue("s", dummy);
pstr = PyEval_CallObject(pfunc, pargs);

PyArg_Parse(pstr, "s", &cstr);
printf("%s\n", cstr);

Py_DECREF(pmod);
Py_DECREF(pstr);
Py_DECREF(pfunc);
Py_DECREF(pargs);


return Py_BuildValue("i", sts);

}

In the same module I am trying to call the python program from C API. That
python program is called test2_module.py. It is listed below -

import string

message = 'Hi I am here'

def cv_calc_func(dummy):
s = "warning" + `dummy`
return s


-----
It contains a method called cv_calc_func(). So now the idea must me clear. I
would need to communicate bi-directionally, i.e. from python to C and C to
python. This example is inspired by the fact that we use the C func from
Numerical recepies in C corresponding to lets say some optimization
algorithm. So that we don't re-invent the wheel in python. So we call a C
API from python. But in the optimization the objective function value must
be returned from a python program, so from C API I should be able to call a
python program and then integrate it with my optimization algorithm.

In this example I have tried to use "PyEval_CallObject()" within the
"myOptim_system" C API function but it reports memory error. But when I call
it from main() it doesn't report any errors.
Just wondering what do I do here?

-regards
Prav
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top