Cython直接访问全局变量



如何在不使用访问器函数的情况下访问Cython声明的全局变量?

我试着用下面的例子:

pyfunktionen_a.pyx

import numpy as np
cdef extern from "funktionen_a.h":
    cdef void setValue(int value_to_set)
    cdef int readValue()
    cdef int value
def pysetValue (_value):
    setValue(_value)
def pyreadValue():
    print readValue()
def manipulateValue(value_to_set):
    value = value_to_set

funktionen_a.c

#include "funktionen_a.h"

void setValue(int value_to_set){
    value = value_to_set;
}
int readValue(){
    return value;
}

funktionen_a.h

#include <Python.h>
#include <stdio.h>

void setValue(int value_to_set);
int readValue();
int value;

通过这个函数,我控制了整个过程:

control.py

import pyfunktionen_a
pyfunktionen_a.pysetValue(8)
pyfunktionen_a.pyreadValue()
pyfunktionen_a.manipulateValue(5)
pyfunktionen_a.pyreadValue()

i 期望的结果:

>>    8
>>    5
::
>>    8
>>    8

您可以尝试使用:

def manipulateValue(value_to_set):
    global value
    value = value_to_set

否则value将是该函数的一个局部变量。

此链接可能有用:https://github.com/cython/cython/wiki/FAQ#id34

最新更新