By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,413 Members | 1,255 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,413 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
- 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);

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 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?

Jul 18 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.