gpt4 book ai didi

python - Cython 直接访问全局变量

转载 作者:行者123 更新时间:2023-11-28 16:36:51 24 4
gpt4 key购买 nike

如何在不使用访问函数的情况下访问用 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()

预期的结果是什么:

>>    8
>> 5

但是我得到的结果是什么:

>>    8
>> 8

最佳答案

您可以尝试使用:

def manipulateValue(value_to_set):
global value
value = value_to_set

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

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

关于python - Cython 直接访问全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24996691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com