Call a Python function from a C program

I have an application in C, and at some point I need to solve the problem of nonlinear optimization. Unfortunately, AFAIK has very limited resources to do this in C (please let me know otherwise). However, this is pretty simple to do in Python, for example. scipy.optimize.minimize .

While I was trying to do this, I came across some of what seemed to be very frequent traps, for example. Python.hnot found, module does not load, segmentation error when calling a function, etc.

What is a quick and easy way for the first timer to link two programs?

+2
source share
1 answer

There are some things you need to make sure that they are created to make this work:

  • Make sure you have Python installed (you may need a package python-dev).
  • Find the file Python.h, for example. on locate Python.h. One of the entries should be in the sub (sub) folder in the folder include, for example. the path should be something like ../include/python2.7/Python.h.
  • Paste #include "<path_to_Python.h>"in your C code to be able to use the Python API.
  • Use any tutorial to call a Python function. I used this one and it did the trick. However, there were several drawbacks:

    • Whenever you use any function Py<Name>, for example. PyImport_Import(), always check the result to make sure there was no error, for example

      // Load the module object
      pModule = PyImport_Import(pName);
      
      if (!pModule)
      {
          PyErr_Print();
          printf("ERROR in pModule\n");
          exit(1);
      }
      
    • Python, .. Py_Initialize();, sys.path, ( ):

      PyObject *sys = PyImport_ImportModule("sys");
      PyObject *path = PyObject_GetAttrString(sys, "path");
      PyList_Append(path, PyString_FromString("."));
      
  • , Python, .py.
  • , /:
    • ../include/python2.7/Python.h, ? include -I gcc , . -I /System/Library/Frameworks/Python.framework/Versions/2.7/include.
    • . , include, . -L /System/Library/Frameworks/Python.framework/Versions/2.7/lib, -lpython2.7 (, Python).

C, Python.

, !

:

+7

Source: https://habr.com/ru/post/1620878/


All Articles