5

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

我该如何解决这个问题?作为一种解决方法,该函数当前接受一个函数参数并调用它,但这不是理想的解决方案。

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

4

3 回答 3

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);
于 2009-10-17T21:15:23.490 回答
3

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

当我想弄清楚如何做这样的事情时,我会查看C API 文档。关于导入模块的部分将有所帮助。您还需要阅读文档中的如何读取属性、调用函数等。

但是我怀疑您真正想要做的是从 C 调用底层库 sdl。这是一个 C 库,并且非常易于从 C 中使用。

这是一些示例代码,用于在 C 中导入 python 模块,改编自一些工作代码

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);
于 2009-10-17T20:59:41.623 回答
0

模块中的大多数函数pygame只是 SDL 函数的包装器,因此您必须在其中查找其函数的 C 版本。pygame.h定义了一系列import_pygame_*()函数。在扩展模块初始化时调用import_pygame_base()和其他一次以访问 pygame 模块的 C API 所需的部分(它在每个模块的头文件中定义)。谷歌代码搜索会给你带来一些例子

于 2009-10-18T07:31:08.893 回答