Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython direct access to Global Variable

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

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
like image 950
python_peter Avatar asked Jul 28 '14 13:07

python_peter


1 Answers

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.

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

like image 51
maggie Avatar answered Sep 30 '22 13:09

maggie