繁体   English   中英

对Python进行C扩展,需要另一个扩展

[英]Making a C extension to Python that requires another extension

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

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

顺便说一句,使用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);

你可以从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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM