次のコードを含む共有ライブラリを作成しました。
#include "Python.h"
extern "C" __declspec(dllexport) PyObject* PyObjectFromAdress(long addr) {
return (PyObject*) addr;
}
それをコンパイルし、ctypesを使用してラップしました:
import ctypes
dll = ctyes.cdll.thedll
object_from_id = dll.PyObjectFromAdress
object_from_id.restype = ctypes.py_object()
これで、1つのPythonプロセス内でメモリアドレスを介してPythonオブジェクトを交換できます。
l1 = []
l2 = object_from_id( id(l1) )
print l1 == l2
l1.append(9)
print l2
ただし、すでにガベージコレクションされたオブジェクトに注意してください。次のコードは、Pythonインタープリターをクラッシュさせます。
l2 = object_from_id( id([]) )
l2.append(8)