对Python进行C扩展需要其他扩展


问题内容

我有几个Python函数,可用来简化Pygame的游戏开发。我在Python路径中将它们保存在一个名为helper.py的文件中,因此可以从我制作的任何游戏中导入它们。我认为,作为学习Python扩展的练习,可以将此模块转换为C。我的第一个问题是我需要使用Pygame中的函数,并且不确定是否可行。Pygame安装了一些头文件,但是它们似乎没有Python函数的C版本。也许我想念一些东西。

我该如何解决?解决方法是,该函数当前接受一个函数参数并对其进行调用,但这不是理想的解决方案。

顺便说一下,使用Windows XP,Python 2.6和Pygame 1.9.1。


问题答案:
/* 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);