-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcall_class.c
68 lines (57 loc) · 1.51 KB
/
call_class.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// A sample of python embedding (calling python classes from within C++ code)
//
// To run:
// 1) setenv PYTHONPATH ${PYTHONPATH}:./
// 2) call_class py_source Multiply multiply
// 3) call_class py_source Multiply multiply 9 8
//
#include <Python.h>
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pClass, *pInstance, *pValue;
int i, arg[8];
if (argc < 4)
{
fprintf(stderr,"Usage: call python_filename class_name function_name\n");
return 1;
}
Py_Initialize();
pName = PyString_FromString(argv[1]);
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
// Build the name of a callable class
pClass = PyDict_GetItemString(pDict, argv[2]);
// Create an instance of the class
if (PyCallable_Check(pClass))
{
pInstance = PyObject_CallObject(pClass, NULL);
}
// Build parameter list
if( argc > 4 )
{
for (i = 0; i < argc - 4; i++)
{
arg[i] = atoi(argv[i + 4]);
}
// Call a method of the class with two parameters
pValue = PyObject_CallMethod(pInstance, argv[3], "(ii)", arg[0], arg[1]);
} else
{
// Call a method of the class with no parameters
pValue = PyObject_CallMethod(pInstance, argv[3], NULL);
}
if (pValue != NULL)
{
printf("Return of call : %d\n", PyInt_AsLong(pValue));
Py_DECREF(pValue);
}
else
{
PyErr_Print();
}
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
Py_Finalize();
return 0;
}