Using python C API in my own C module

This is similar to what I want, except that I want to create an instance of C PyObject in another C module.

Create an instance of a python class declared in python with the API API

But I cannot find documentation for using the Python module from C. I cannot find suitable documents on the Internet, since everyone is just talking about the Python extension using C.

My problem is that I have Pygame that I want to speed up. Therefore, I am creating a C module that needs access to Pygame. How to import pygame? I do not want to import two copies, right? I encode the part that I can figure out, I just don’t know how to configure and link the code. I know that I need to skip some documents, so if someone could point me in the right direction, I would be very obliged.


Update: Sorry, I re-read my post and realized that my wording is terrible.

If you have pygame installed, you can look in your Python / include directory and find the pygame header files. What are they for? I thought your C module could directly access the pygame C module, so your python script AND your C module used the same pygame instance.

Refining anyone?

+3
source share
3 answers

The trick is to write a regular Python routine, but in C. Use PyImport_ImportModule(), PyObject_GetAttr()and PyObject_Call()if necessary.

+1
source

I made it out in one "I was lucky."

0
source

pygame C-API, , , ( , pygame pygame).

, "" API, , , / pygame, pygame API/ABI C...

, :

C (red.c):

#include <Python.h>
#include <pygame/pygame.h>

static PyObject* fill_surface(PyObject* self, PyObject* args)
{
  PyObject* py_surface = NULL;
  if( !PyArg_ParseTuple(args, "O", &py_surface) )
    return NULL;

  PySurfaceObject* c_surface = (PySurfaceObject*) py_surface;
  SDL_FillRect( c_surface->surf, 0, SDL_MapRGB(c_surface->surf->format, 255, 0, 0) );

  return Py_None;
}

PyMethodDef methods[] = {

  {"fill_surface", fill_surface, METH_VARARGS, "Paints surface red"},
  {NULL, NULL, 0, NULL},
};

void initred()
{
  Py_InitModule("red", methods);
}

Makefile (Linux):

SOURCES = red.c
OBJECTS = $(SOURCES:.c=.o)
TARGET = red.so

CFLAGS += -Wall -O2 -g
CFLAGS += $(shell python-config --cflags)
CFLAGS += $(shell sdl-config --cflags)

LDFLAGS += $(shell sdl-config --libs)

all: $(TARGET)

clean:
    $(RM) $(OBJECTS)
    $(RM) $(TARGET)

$(TARGET): $(OBJECTS)
    $(CC) -shared -o $@ $(OBJECTS) $(LDFLAGS)

$(OBJECTS): Makefile

Python:

import pygame
import red

pygame.init()
screen = pygame.display.set_mode( (640, 480) )
red.fill_surface(screen)
pygame.display.update()
pygame.time.delay(3000)
0
source

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


All Articles