红糖糍粑
我猜想pythonic的方法是让不同的扩展通过C API进行交互。尽管我对c ++不太了解,但我想它与C中的解决方案并没有太大区别。我可以通过以下方式做到这一点:在模块A中定义全局变量为模块A定义一个C API,其中包含指向全局变量的指针(如果需要,还可以包含一个宏,以方便使用)。在模块B中加载C API并通过指针访问全局变量。编写用于python C扩展的C API涉及到一些工作。(如果您不熟悉Python C API,请阅读python文档。)我建议的解决方案的最小示例如下所示:A.h/* Header file for A module */#ifndef A_MODULE_H#define A_MODULE_H#ifdef __cplusplusextern "C" {#endif#define PyA_GET_X() (*x_ptr)#define PyA_SET_X(x) (*x_ptr = x)#ifdef A_MODULE/* do nothing for this minimal example */#elsestatic void **PyA_API;#define x_ptr ((long *)PyA_API[0])static int import_A(void){ PyA_API = (void **)PyCapsule_Import("A._C_API", 0); return (PyA_API != NULL) ? 0 : -1;}#endif /* !defined(A_MODULE) */#ifdef __cplusplus}#endif#endif /* !defined(A_MODULE_H) */A.c#include <Python.h>#define A_MODULE#include "A.h"long x = 0; /* here is the global variable */static PyObject* set_x(PyObject *self, PyObject *args){ if (!PyArg_ParseTuple(args, "l", &x)) return NULL; Py_RETURN_NONE;}static PyObject* get_x(PyObject *self, PyObject *args){ return PyInt_FromLong(x);}static PyMethodDef methods[] = { {"set_x", (PyCFunction)set_x, METH_VARARGS, ""}, {"get_x", (PyCFunction)get_x, METH_NOARGS, ""}, {NULL, NULL, 0, NULL} };#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */#define PyMODINIT_FUNC void#endifPyMODINIT_FUNC initA(void){ PyObject *m = Py_InitModule3("A", methods, ""); static void *PyA_API[1]; PyA_API[0] = (void *)&x; PyObject *c_api_object = PyCapsule_New((void *)PyA_API, "A._C_API", NULL); if (c_api_object != NULL) PyModule_AddObject(m, "_C_API", c_api_object);}B.c#include <Python.h>#define B_MODULE#include "A.h"static PyObject* set_x(PyObject *self, PyObject *args){ long y; if (!PyArg_ParseTuple(args, "l", &y)) return NULL; PyA_SET_X(y); Py_RETURN_NONE;}static PyObject* get_x(PyObject *self, PyObject *args){ return PyInt_FromLong(PyA_GET_X());}static PyMethodDef methods[] = { {"set_x", (PyCFunction)set_x, METH_VARARGS, ""}, {"get_x", (PyCFunction)get_x, METH_NOARGS, ""}, {NULL, NULL, 0, NULL} };#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */#define PyMODINIT_FUNC void#endifPyMODINIT_FUNC initB(void){ import_A(); Py_InitModule3("B", methods, "");}setup.pyfrom numpy.distutils.core import setup, Extensionsetup( name="AB", ext_modules = [Extension('A', ['A.c']), Extension('B', ['B.c'])], )最后,您将能够x从两个模块(C级或python)读取和修改。在python中,它看起来像:>>> import A, B>>> A.set_x(1)>>> B.get_x() 1>>> B.set_x(2)>>> A.get_x() 2要从C级访问,请使用宏PyA_GET_X()和PyA_SET_X(x)。