在.pyx文件中导入非整数常量 [英] Import non-integer constant in .pyx file

查看:73
本文介绍了在.pyx文件中导入非整数常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何声明常量(各种类型-不仅仅是枚举值),并在多个 .pyx 文件之间共享它们?

How can I declare constants (of various types - not just enum values) and share them between multiple .pyx files?

.pyx 文件中,我可以声明和使用常量:

Within a .pyx file, I can declare and use constants:

DEF FavouriteFood = "spam"
DEF ArraySize = 42
print(FavouriteFood)
print(ArraySize)

然后使用 .pxd 文件,我可以共享C函数共享类型

And using a .pxd file, I can share C functions or share types.

但是如何共享常量?文档指出使用此方法的方法非常有限匿名枚举,但其中的值只能是整数。例如,如何导入常量字符串或浮点到 .pyx 文件中?

But how can I share constants? The docs indicate a very limited way of doing this with anonymous enums, but values in those can only be ints. How can I import, for example, a constant string or float into a .pyx file?

推荐答案

您可以在pxd文件中使用非常短的内联函数( )只是返回常量

You could use a very short inline function (in the pxd file) that just returns the constant

cdef inline const char* GetFavouriteFood():
    return "spam"

cdef inline float GetHowMuch():
    return 4.5

另一个选择是在头文件中定义C中的常量,然后(在pxd中)执行

The other option would be to define the constants in C in a header file then (in your pxd) do

cdef extern from "myconstants.h":
   const char* FavouriteFood
   float HowMuch

The C编译器(而不是Cython)强制执行常量性,因此,如果尝试更改它们,错误将在该阶段出现。这确实涉及创建一个额外的文件,所以我个人更喜欢内联函数方法。

The C compiler (rather than Cython) enforces the constness so errors will appear at that stage if you try to change them. This does involve create an extra file so personally I prefer the inline function approach.

编辑(2018):

您现在可以直接在Cython中包含C代码,这使第二种方法更容易:

You can now include C code directly in Cython which makes the second approach easier:

cdef extern from *:
   """const char* FavouriteFood = "spam";
   const float HowMuch = 4.5;"""
   const char* FavouriteFood
   float HowMuch

这篇关于在.pyx文件中导入非整数常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆