2009-10-17 105 views
5

我有一些Python函数可以让我们更容易地使用Pygame进行游戏开发。我把它们放在我的Python路径中的helper.py文件中,这样我就可以从我制作的任何游戏中导入它们。我认为,作为学习Python扩展的练习,将此模块转换为C。我的第一个问题是我需要使用Pygame中的函数,但我不确定这是否可行。 Pygame安装了一些头文件,但它们似乎没有C函数的Python版本。也许我错过了一些东西。制作需要另一个扩展名的Python的C扩展

我该如何解决这个问题?作为一种解决方法,函数当前接受函数参数并调用该函数,但这不是理想的解决方案。顺便说一下,使用Windows XP,Python 2.6和Pygame 1.9.1。

回答

6
/* get the sys.modules dictionary */ 
PyObject* sysmodules PyImport_GetModuleDict(); 
PyObject* pygame_module; 
if(PyMapping_HasKeyString(sysmodules, "pygame")) { 
    pygame_module = PyMapping_GetItemString(sysmodules, "pygame"); 
} else { 
    PyObject* initresult; 
    pygame_module = PyImport_ImportModule("pygame"); 
    if(!pygame_module) { 
     /* insert error handling here! and exit this function */ 
    } 
    initresult = PyObject_CallMethod(pygame_module, "init", NULL); 
    if(!initresult) { 
     /* more error handling &c */ 
    } 
    Py_DECREF(initresult); 
} 
/* use PyObject_CallMethod(pygame_module, ...) to your heart's contents */ 
/* and lastly, when done, don't forget, before you exit, to: */ 
Py_DECREF(pygame_module); 
3

你可以从C代码中导入python模块,并像在python代码中那样调用定义的东西。这有点长,但完全可能。

当我想弄清楚如何做这样的事情时,我看看C API documentation。有关importing modules的部分将有所帮助。您还需要阅读如何阅读文档中的属性,调用函数等。

不过,我怀疑你真正想要做的是从调用C的underlying library sdl这是一个C库,是很容易从C

使用

下面是一些示例代码导入在C Python模块改编自位pygame模块工作代码

PyObject *module = 0; 
PyObject *result = 0; 
PyObject *module_dict = 0; 
PyObject *func = 0; 

module = PyImport_ImportModule((char *)"pygame"); /* new ref */ 
if (module == 0) 
{ 
    PyErr_Print(); 
    log("Couldn't find python module pygame"); 
    goto out; 
} 
module_dict = PyModule_GetDict(module); /* borrowed */ 
if (module_dict == 0) 
{ 
    PyErr_Print(); 
    log("Couldn't find read python module pygame"); 
    goto out; 
} 
func = PyDict_GetItemString(module_dict, "pygame_function"); /* borrowed */ 
if (func == 0) 
{ 
    PyErr_Print(); 
    log("Couldn't find pygame.pygame_function"); 
    goto out; 
} 
result = PyEval_CallObject(func, NULL); /* new ref */ 
if (result == 0) 
{ 
    PyErr_Print(); 
    log("Couldn't run pygame.pygame_function"); 
    goto out; 
} 
/* do stuff with result */ 
out:; 
Py_XDECREF(result); 
Py_XDECREF(module); 
0

大部分功能都只是围绕SDL函数的包装,那就是你要寻找它的功能C版。 pygame.h定义了一系列import_pygame_*()函数。在扩展模块初始化时调用import_pygame_base()和其他一次,以访问pygame模块的C API所需的部分(它在每个头文件中定义)。 Google代码搜索会为您带来some examples