Cython将变量设置为命名常量

时间:2018-07-20 04:37:26

标签: cython cythonize

我正在追逐我怀疑是一个简单问题的尾巴,但是对于所观察到的行为,我似乎找不到任何解释。假设我在C头文件中有一个常量,定义如下:

#define FOOBAR 128
typedef uint32_t mytype_t;

我将以下内容放入.pxd文件,以在Cython中进行转换:

cdef int _FOOBAR   "FOOBAR"
ctypedef uint32_t mytype_t

在我的.pyx文件中,有一个声明:

FOOBAR = _FOOBAR

后面是类定义:

cdef class MyClass:
    cdef mytype_t myvar
    def __init__(self):
        try:
            self.myvar = FOOBAR
            print("GOOD")
        except:
            print("BAD")

然后我尝试使用一个简单的程序执行此操作:

try:
    foo = MyClass()
except:
    print("FAILED TO CREATE CLASS")

不幸的是,这个错误出来了,但是我没有收到错误消息-我只是获得了异常打印输出:

BAD

任何关于根本原因的建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

我相信我终于找到了它。根本原因是我的代码中的 import { Injectable, Injector } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import { ToasterService } from 'angular2-toaster'; import { AuthService } from 'app/blocks/auth/auth.service'; import { TranslateService } from 'ng2-translate'; import { AlertService } from '../../core/services/common'; @Injectable() export class AppHttpInterceptor implements HttpInterceptor { constructor(private injector: Injector) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { debugger; console.log(req); if (!window.navigator.onLine) { // check to see if there's internet // if there is no internet, throw a HttpErrorResponse error // since an error is thrown, the function will terminate here return Observable.throw(new HttpErrorResponse({ error: 'NO_INTERNET' })); } else { // else return the normal request return this.handleResponse(next, req); } } handleResponse(next, req) { return next.handle(req) .do((ev: HttpEvent<any>) => { if (ev instanceof HttpResponse) { } }) .catch((response: any) => { if (response instanceof HttpErrorResponse) { console.log('response in the catch: ', response); this.handleReponseExceptions(response); } return Observable.throw(response); }); } handleReponseExceptions(exception) { let toaster = this.injector.get(ToasterService); let translate = this.injector.get(TranslateService); // TOASTER NOT WORKING AND TRANSLATE NOT WORKING toaster.pop("test","test"); this.translate.get(["test", "test"]).subscribe(res => { //NOT FETCHING FROM en.json }); } } 实际上设置为FOOBAR。显然,Cython / Python将其解释为UINT32MAX,然后Python拒绝设置与其相等的-1变量。解决方案是将uint32_t定义为FOOBAR-显然Python认为这是一个非负值,并接受它。