LINUX.ORG.RU

История изменений

Исправление ei-grad, (текущая версия) :

Но на ctypes наверное попроще - https://chat.openai.com/share/5266b840-6f79-4e3f-bd67-342478203d05

In order to call a C function from Python, you can use the ctypes or cffi libraries, or the Cython tool. Below are steps using ctypes:

  1. C Code Preparation:

    • Create a file named func4py.c with the following content:
      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      
      char* func4py(const char* data, int data_size, int pos, const char* buf, int buf_size) {
          char* res = (char*) malloc(buf_size + pos);
          // ...
          return res;
      }
      
  2. Compilation:

    • Compile func4py.c into a shared library:
      gcc -shared -o libfunc4py.so -fPIC func4py.c
      
  3. Python Wrapper:

    • Create a file named wrapper.py with the following content:
      import ctypes
      
      # Load the shared library
      lib = ctypes.CDLL('./libfunc4py.so')
      
      def func4py(buf1, pos, buf2):
          # Convert Python bytes objects to ctypes char pointers
          c_buf1 = ctypes.create_string_buffer(buf1)
          c_buf2 = ctypes.create_string_buffer(buf2)
      
          # Call the C function
          c_res = lib.func4py(c_buf1, len(buf1), pos, c_buf2, len(buf2))
      
          # Convert the result to a Python bytes object
          res_size = len(buf2) + pos
          res = ctypes.string_at(c_res, res_size)
      
          # Free the allocated memory in C (optional, but recommended)
          ctypes.CDLL('libc.so.6').free(c_res)
      
          return res
      
      # Usage
      buf1 = b'data1'
      pos = 5
      buf2 = b'data2'
      buf3 = func4py(buf1, pos, buf2)
      print(buf3)
      

In the func4py Python function, ctypes.create_string_buffer is used to convert Python bytes objects to ctypes char arrays. The ctypes.CDLL function is used to load the shared library, and ctypes.string_at is used to convert the result back to a Python bytes object. Finally, ctypes.CDLL('libc.so.6').free is used to free the allocated memory in C, which is optional but recommended to prevent memory leaks.

Now, you can call func4py from Python as you desired:

buf3 = func4py(buf1, pos, buf2)

Исходная версия ei-grad, :

Но на ctypes наверное попроще - https://chat.openai.com/share/5266b840-6f79-4e3f-bd67-342478203d05