Код: Выделить всё
// main.c
#include
#include
#include // Adding required inclusion for printf
int main() {
// Initialize the Python interpreter
Py_Initialize();
// Import the Python module that contains our functions
PyObject *pModule = PyImport_ImportModule("funcoes_python");
// Checks if the import was successful
if (pModule != NULL) {
// Gets the references to the functions we want to call
PyObject *pFuncSoma = PyObject_GetAttrString(pModule, "soma");
PyObject *pFuncSubtracao = PyObject_GetAttrString(pModule, "subtracao");
// Call the functions and print the results
if (pFuncSoma && PyCallable_Check(pFuncSoma)) {
PyObject *pArgs = PyTuple_Pack(2, PyLong_FromLong(10), PyLong_FromLong(5));
PyObject *pResult = PyObject_CallObject(pFuncSoma, pArgs);
long result = PyLong_AsLong(pResult);
printf("Soma: %ld\n", result);
Py_XDECREF(pArgs);
Py_XDECREF(pResult);
}
if (pFuncSubtracao && PyCallable_Check(pFuncSubtracao)) {
PyObject *pArgs = PyTuple_Pack(2, PyLong_FromLong(10), PyLong_FromLong(5));
PyObject *pResult = PyObject_CallObject(pFuncSubtracao, pArgs);
long result = PyLong_AsLong(pResult);
printf("Subtracao: %ld\n", result);
Py_XDECREF(pArgs);
Py_XDECREF(pResult);
}
// Release references
Py_XDECREF(pFuncSoma);
Py_XDECREF(pFuncSubtracao);
} else {
PyErr_Print();
}
// End the Python interpreter
Py_Finalize();
return 0;
}
Код: Выделить всё
# funcoes_python.py
def soma(a, b):
return a + b
def subtracao(a, b):
return a - b
Код: Выделить всё
g++ main.c -o output -L C:/Python312/libs -lpython3 -I C:/Python312/include
.\output.exe
Это должно быть напечатано:
Код: Выделить всё
Sum: 15
Subtraction: 5
Конфигурация:
- Python 3.12
- Windows 10 SO
Подробнее здесь: https://stackoverflow.com/questions/784 ... thon-c-api