如何将视频内存从Python映射到C?

klu*_*utt 6 c python graphics python-3.x

我一直在用 Python 处理一些简单的图形问题,但为了提高性能,我想用 C 做一些事情。

\n

我知道如何来回传输数组和内容。这没什么大不了的。但我认为,如果我可以创建一个带有画布的窗口,传递一个指向视频内存(当然不是物理视频内存)的指针,然后让Python负责将该内存放到屏幕上,那么这可能会很有用。其余的都是在 C 中完成的。可能是异步的,但我不\xcd\x84 不知道这是否重要。

\n

这可能吗?有意义吗?或者我完全走错了路?

\n

到目前为止我的努力:

\n
# graphics.py\n\nimport ctypes\nimport pygame\n\nscreen = pygame.display.set_mode((300,200))\n\nf = ctypes.CDLL('/path/to/engine.so')\n\nf.loop(screen._pixels_address)\n
Run Code Online (Sandbox Code Playgroud)\n

\n
// engine.c\n\n#include <stdint.h>\n\nvoid loop(void *mem) {\n    while(1) {\n        uint8_t *p = (uint8_t*) mem;\n      \n        // Was hoping this would make some pixels change\n        for(int i=0; i<20000; i++)\n            *p=127;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

这不起作用并最终导致崩溃。我并不感到惊讶,但是,这就是我到目前为止所得到的。

\n

并不是绝对有必要使用Python。但我确实想使用 C。而且我也知道,在大多数情况下,我的方法不是最好的方法,但我确实喜欢用 C 编码并做一些老派的事情。

\n

mni*_*tic 3

大多数 GUI 工具包和游戏库都会提供一种或另一种访问像素缓冲区的方法。

一个简单的入门方法是使用 pygame。pygame 的get_buffer().raw数组可以Surface传递到 C 程序中。

import pygame

background_colour = (255,255,255) # For the background color of your window
(width, height) = (300, 200) # Dimension of the window

screen = pygame.display.set_mode((width, height))

f = CDLL('engine.so')
f.loop(screen.get_buffer().raw)
Run Code Online (Sandbox Code Playgroud)