【发布时间】:2021-10-08 05:30:58
【问题描述】:
我正在尝试在 C 中为 numpy 定义一个自定义类型,并且首先想了解代码。查看 numpy Github 存储库,很多 C 函数的定义中都有“NPY_INLINE”。这在代码中究竟做了什么?
例如:
static NPY_INLINE int
npy_is_aligned(const void * p, const npy_uintp alignment)
谢谢!
【问题讨论】:
我正在尝试在 C 中为 numpy 定义一个自定义类型,并且首先想了解代码。查看 numpy Github 存储库,很多 C 函数的定义中都有“NPY_INLINE”。这在代码中究竟做了什么?
例如:
static NPY_INLINE int
npy_is_aligned(const void * p, const npy_uintp alignment)
谢谢!
【问题讨论】:
它的定义可以在npy_common.h头文件中找到。
// these comments are added by me.
// check if the compiler is MSVC.
#if defined(_MSC_VER)
// use the vendor-specific keyword, modern
// versions of MSVC also support inline.
#define NPY_INLINE __inline
// check if the compiler supports the GNU C extensions,
// that includes for example GCC and Clang among others.
#elif defined(__GNUC__)
// check if the compiler expects strictly C89.
#if defined(__STRICT_ANSI__)
// use the vendor-specific keyword.
#define NPY_INLINE __inline__
#else
// if not strictly C89, use standard keyword.
#define NPY_INLINE inline
#endif
#else
// if it can't be sure, it simply doesn't try.
#define NPY_INLINE
#endif
这样做是尝试将内联说明符添加到 C 版本和编译器无关的函数定义中,因为 内联函数说明符 (6.7.4) 是仅在 C99 中添加。这是对编译器的建议,该函数应该被内联。编译器可以选择是否应该尊重它。
至于什么是内联函数:它相当于您将函数的内容复制粘贴到将被调用的位置。这消除了调用函数的开销,但还有其他缺点。有关其效果、用法和历史的更完整信息,wikipedia 总是很可爱。
玩得开心编码! :)
【讨论】: