I have a static library (or a bunch of c/cpp-files for that matter) which contains a singleton and is used by/linked to two different C-extensions. However, the singleton from the C-library doesn't behave like a singleton anymore:
import getter
import setter
# set singleton:
setter.set(21)
# get singleton:
print("singleton: ", getter.get())
#prints the old value:42
Here is a minimal example illustrating this problem using Cython for the sake of simplicity (all files are in the same folder):
C-library:
//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;
}
The two Cython extensions:
# 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)
A setup-file following this 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"]}) ]
)
After building via python setup.py build_clib build_ext --inplace, the above python script can be run.
What is the correct way to share a C-singleton between multiple (Cython)-C-extensions?