1
+ #include < Python.h>
2
+
3
+ // CPP functions that will be called from Python
4
+ static PyObject *functionFromCPP (PyObject *self, PyObject *args)
5
+ {
6
+ printf (" This message comes from CPP\n " );
7
+ return Py_BuildValue (" s" , " Hello from CPP" );
8
+ }
9
+
10
+ static PyObject *functionFromCPP2 (PyObject *self, PyObject *args)
11
+ {
12
+ int a, b;
13
+ if (!PyArg_ParseTuple (args, " ii" , &a, &b))
14
+ return NULL ;
15
+ printf (" The sum of %d and %d is %d\n " , a, b, a + b);
16
+ return Py_BuildValue (" i" , a + b);
17
+ }
18
+
19
+ // CPP Variables that will be used in Python
20
+ static PyObject *variableFromCPP = PyLong_FromLong(42 );
21
+ static PyObject *variableFromCPP2 = Py_BuildValue(" s" , " Hello from CPP variable 2" );
22
+
23
+ // Method definition structure
24
+ static PyMethodDef MyMethods[] = {
25
+ // Method definition structure
26
+ {" functionFromCPP" , functionFromCPP, METH_VARARGS, " Function from CPP" },
27
+ {" functionFromCPP2" , functionFromCPP2, METH_VARARGS, " Function from CPP with arguments" },
28
+ {NULL , NULL , 0 , NULL } // Sentinel
29
+ };
30
+
31
+ // Module definition to register the module
32
+ static struct PyModuleDef etkindmodule = {
33
+ PyModuleDef_HEAD_INIT,
34
+ " pycmtemplate_c" , // Module name
35
+ NULL , // Module documentation
36
+ -1 , // Size of per-interpreter state
37
+ MyMethods};
38
+
39
+ // Module initialization
40
+ PyMODINIT_FUNC PyInit_pycmtemplate_c (void )
41
+ {
42
+ // Create the module
43
+ PyObject *module = PyModule_Create (&etkindmodule);
44
+ if (module == NULL )
45
+ return NULL ;
46
+
47
+ // Add variables to the module
48
+ PyModule_AddObject (module , " variableFromCPP" , variableFromCPP);
49
+ PyModule_AddObject (module , " variableFromCPP2" , variableFromCPP2);
50
+
51
+ return module ;
52
+ }
0 commit comments