I am searching a very small and simple sample to load a python module in C app. everywhere i search I see long example and I am not understand. If this is duplicate share stackoverflow link and I will delete this question. Thank you and i am new to Python.
Asked
Active
Viewed 193 times
1 Answers
4
Create a Python Module name reverse.py as below:
def rstring(s):
i = len(s)-1
t = ''
while(i > -1):
t += s[i]
i -= 1
return t
Create a C application as below:
#include <Python.h>
int main()
{
PyObject *strret, *mymod, *strfunc, *strargs;
char *cstrret;
Py_Initialize();
PySys_SetPath(".");
mymod = PyImport_ImportModule("reverse");
strfunc = PyObject_GetAttrString(mymod, "rstring");
strargs = Py_BuildValue("(s)", "Hello World");
strret = PyEval_CallObject(strfunc, strargs);
PyArg_Parse(strret, "s", &cstrret);
printf("Reversed string: %s\n", cstrret);
Py_Finalize();
return 0;
}
Now be sure to keep the reverse.py and your C application in the same folder. After that please compile and run C Sample Application.
Please study the each line in above sample, as there are about 20 total lines and if you have question about any line please let me know, I would be pleased to answer.
Credit goes to the SO Link here as I have corrected those samples: Embedding Python into C - importing modules

Community
- 1
- 1

AvkashChauhan
- 20,495
- 3
- 34
- 65
-
thanks, as simple as i was searching. – May 26 '12 at 16:52