Cython直接访问全局变量

时间:2021-03-26 00:41:21

How can I access a global variable declared with Cython, without using a accessor function?

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

I tried with following example:

我尝试了以下示例:

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;

And with this function I control the whole thing:

有了这个功能,我控制了整个事情:

control.py

import pyfunktionen_a

pyfunktionen_a.pysetValue(8)
pyfunktionen_a.pyreadValue()

pyfunktionen_a.manipulateValue(5)
pyfunktionen_a.pyreadValue()

What results i expected:

我的预期结果如何:

>>    8
>>    5

But what results i get:

但是我得到了什么结果:

>>    8
>>    8

1 个解决方案

#1


2  

You can try using:

您可以尝试使用:

def manipulateValue(value_to_set):
    global value
    value = value_to_set

Otherwise value will be a local variable in this function.

否则value将是此函数中的局部变量。

This link could be useful: https://github.com/cython/cython/wiki/FAQ#id34

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

#1


2  

You can try using:

您可以尝试使用:

def manipulateValue(value_to_set):
    global value
    value = value_to_set

Otherwise value will be a local variable in this function.

否则value将是此函数中的局部变量。

This link could be useful: https://github.com/cython/cython/wiki/FAQ#id34

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