在使用debug-build时,处理C扩展的“\d”后缀的最佳方法是什么?

2024-10-01 19:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在调试python2.7的C扩展。我使用python2.7调试构建。我用setuptools构建我的项目,我的setup.py有这样的行:

ext_modules=[Extension("my.extension",
                       ["my/_extension.c"])]

当我出于某种原因调用python setup.py install时,扩展将编译成后缀为_d的文件,之后,在Python中,我不能执行import my.extension,只能执行import my.extension_d。我得到的是:

^{pr2}$

当然,我的扩展没有initextension_d,它只有initextension函数。在

这非常不方便,因为我必须更改一些代码,并在imports和其他东西中添加这个_d后缀。在

可以关闭这个后缀的前缀吗?或者如何以其他方式处理这个问题?也许有一些“官方”的方式?在

更新#0

我用的是Ubuntu Linux。在


Tags: install项目pyimportmodulesmy方式setup
3条回答

只需在构建C扩展时禁用调试模式。 或者,如果您想保留调试信息,请临时禁用_DEBUG宏:

#ifdef _DEBUG
# ifndef BOOST_DEBUG_PYTHON
#  ifdef _MSC_VER  
    // VC8.0 will complain if system headers are #included both with
    // and without _DEBUG defined, so we have to #include all the
    // system headers used by pyconfig.h right here.
#   include <stddef.h>
#   include <stdarg.h>
#   include <stdio.h>
#   include <stdlib.h>
#   include <assert.h>
#   include <errno.h>
#   include <ctype.h>
#   include <wchar.h>
#   include <basetsd.h>
#   include <io.h>
#   include <limits.h>
#   include <float.h>
#   include <string.h>
#   include <math.h>
#   include <time.h>
#  endif
#  undef _DEBUG // Don't let Python force the debug library just because we're debugging.
#  define DEBUG_WRAP_PYTHON_H
# endif
#endif

#include <Python.h>

#ifdef DEBUG_WRAP_PYTHON_H
# define _DEBUG
#endif

对于完整的代码示例,您可以看看full version如何boost.python包括python.h。在

来自build_ext.py的distutils源文件的注释:

# extensions in debug_mode are named 'module_d.pyd' under windows

对于C扩展也是一样的,所以应该不会有任何问题。但既然有一个,也可以去掉_d后缀:

import os.path
from setuptools.command.build_ext import build_ext as _build_ext

class build_ext(_build_ext):
    def get_ext_filename(self, ext_name):
        fn = _build_ext.get_ext_filename(self, ext_name)
        fn = os.path.splitext(fn)
        if fn[0].endswith('_d'):
            fn[0] = fn[0][:-2]
        return fn[0] + fn[1]

或者暂时禁用调试:

^{pr2}$

别忘了在setup内设置cmdclass

setup(
    ...
    cmdclass={'build_ext': build_ext},
    ...
)

我自己并不是在使用Windows,所以这只是一个猜测,但也许你在混合Python的调试和发布部分。在

要解决这个问题,可以在C模块函数中定义

void initextension_d()
{ initextension(); }

相关问题 更多 >

    热门问题