1 | n/a | #include <Python.h> |
---|
2 | n/a | |
---|
3 | n/a | int |
---|
4 | n/a | main(int argc, char *argv[]) |
---|
5 | n/a | { |
---|
6 | n/a | PyObject *pName, *pModule, *pDict, *pFunc; |
---|
7 | n/a | PyObject *pArgs, *pValue; |
---|
8 | n/a | int i; |
---|
9 | n/a | |
---|
10 | n/a | if (argc < 3) { |
---|
11 | n/a | fprintf(stderr,"Usage: call pythonfile funcname [args]\n"); |
---|
12 | n/a | return 1; |
---|
13 | n/a | } |
---|
14 | n/a | |
---|
15 | n/a | Py_Initialize(); |
---|
16 | n/a | pName = PyUnicode_DecodeFSDefault(argv[1]); |
---|
17 | n/a | /* Error checking of pName left out */ |
---|
18 | n/a | |
---|
19 | n/a | pModule = PyImport_Import(pName); |
---|
20 | n/a | Py_DECREF(pName); |
---|
21 | n/a | |
---|
22 | n/a | if (pModule != NULL) { |
---|
23 | n/a | pFunc = PyObject_GetAttrString(pModule, argv[2]); |
---|
24 | n/a | /* pFunc is a new reference */ |
---|
25 | n/a | |
---|
26 | n/a | if (pFunc && PyCallable_Check(pFunc)) { |
---|
27 | n/a | pArgs = PyTuple_New(argc - 3); |
---|
28 | n/a | for (i = 0; i < argc - 3; ++i) { |
---|
29 | n/a | pValue = PyLong_FromLong(atoi(argv[i + 3])); |
---|
30 | n/a | if (!pValue) { |
---|
31 | n/a | Py_DECREF(pArgs); |
---|
32 | n/a | Py_DECREF(pModule); |
---|
33 | n/a | fprintf(stderr, "Cannot convert argument\n"); |
---|
34 | n/a | return 1; |
---|
35 | n/a | } |
---|
36 | n/a | /* pValue reference stolen here: */ |
---|
37 | n/a | PyTuple_SetItem(pArgs, i, pValue); |
---|
38 | n/a | } |
---|
39 | n/a | pValue = PyObject_CallObject(pFunc, pArgs); |
---|
40 | n/a | Py_DECREF(pArgs); |
---|
41 | n/a | if (pValue != NULL) { |
---|
42 | n/a | printf("Result of call: %ld\n", PyLong_AsLong(pValue)); |
---|
43 | n/a | Py_DECREF(pValue); |
---|
44 | n/a | } |
---|
45 | n/a | else { |
---|
46 | n/a | Py_DECREF(pFunc); |
---|
47 | n/a | Py_DECREF(pModule); |
---|
48 | n/a | PyErr_Print(); |
---|
49 | n/a | fprintf(stderr,"Call failed\n"); |
---|
50 | n/a | return 1; |
---|
51 | n/a | } |
---|
52 | n/a | } |
---|
53 | n/a | else { |
---|
54 | n/a | if (PyErr_Occurred()) |
---|
55 | n/a | PyErr_Print(); |
---|
56 | n/a | fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); |
---|
57 | n/a | } |
---|
58 | n/a | Py_XDECREF(pFunc); |
---|
59 | n/a | Py_DECREF(pModule); |
---|
60 | n/a | } |
---|
61 | n/a | else { |
---|
62 | n/a | PyErr_Print(); |
---|
63 | n/a | fprintf(stderr, "Failed to load \"%s\"\n", argv[1]); |
---|
64 | n/a | return 1; |
---|
65 | n/a | } |
---|
66 | n/a | if (Py_FinalizeEx() < 0) { |
---|
67 | n/a | return 120; |
---|
68 | n/a | } |
---|
69 | n/a | return 0; |
---|
70 | n/a | } |
---|