我有一个静态库(或一堆 c/cpp 文件),其中包含一个单例,并由/链接到两个不同的 C 扩展使用。然而,C 库中的单例不再表现得像单例:
import getter
import setter
# set singleton:
setter.set(21)
# get singleton:
print("singleton: ", getter.get())
#prints the old value:42
为了简单起见,下面是一个使用 Cython 说明此问题的最小示例(所有文件都位于同一文件夹中):
C 库:
//lib.h:
int get_singleton(void);
void set_singleton(int new_val);
//lib.c:
#include "lib.h"
static int singleton=42;
int get_singleton(void){
return singleton;
}
void set_singleton(int new_val){
singleton=new_val;
}
两个 Cython 扩展:
# getter.pyx:
#cython: language_level=3
cdef extern from "lib.h":
int get_singleton()
def get():
return get_singleton()
# setter.pyx:
#cython: language_level=3
cdef extern from "lib.h":
void set_singleton(int new_val);
def set(new_val):
set_singleton(new_val)
此SO-post之后的安装文件:
#setup.py
from setuptools import setup, find_packages, Extension
setup(
name='singleton_example',
ext_modules=[Extension('getter', sources=['getter.pyx']),
Extension('setter', sources=['setter.pyx']),],
# will be build as static libraries and automatically passed to linker for all extensions:
libraries = [('static_lib', {'sources': ["lib.c"]}) ]
)
通过 构建后python setup.py build_clib build_ext --inplace,可以运行上面的 python 脚本。
在多个 (Cython)-C-扩展之间共享 C-单例的正确方法是什么?
湖上湖
相关分类