wlav / cpycppyy Goto Github PK
View Code? Open in Web Editor NEWLicense: Other
License: Other
EDIT: originally this was a feature request to add weak reference support to the LowLevelView type. After discussion it seems like adding support for a __dict__
is a better solution.
I have a specific use case for this I will explain below. However I'm open to suggestions for alternative solutions. I looked into using special variables and couldn't come up with a solution, though I must admit I'm not very confident about my understanding of what these variables do.
Suppose I have C++ functions that return std::vector
. The goal is to turn these into numpy arrays without copying any data. The challenge is I want to be able to keep the underlying C++ objects alive until no python object is referencing the LowLevelView anymore.
To illustrate the issue, consider this code:
import cppyy
import numpy as np
cppyy.cppdef("""
#include <numeric>
static std::vector<int> VectorFunc(size_t len)
{
std::vector<int> ret(len);
std::iota(ret.begin(), ret.end(), 0);
return ret;
}
""")
VectorFunc = cppyy.gbl.VectorFunc
def vector_func(size):
vec = VectorFunc(size)
arr = np.frombuffer(vec.data(), dtype=np.int32)
# at this point, arr is completely valid because we still have a reference to vec
# arr.base is a LowLevelView object.
print(arr)
return arr
arr = vector_func(5)
print(arr)
Output:
[0 1 2 3 4]
[-1689064896 41504 499 0 4]
We know we need to keep the C++ vector alive for as long as anything is referencing the LowLevelView object pointing to vec.data()
. One way to do this is to wrap the LowLevelView object with a small wrapper class that also stores a reference to vec and make sure arr.base
points to an instance of this class. The issue is this wrapper class needs to "forward" the buffer protocol, i.e. it needs to present the buffer protocol from its LowLevelView member to its callers. I don't think this is currently possible. PEP688 may change this starting in 3.12.
Another way to achieve the same behavior would be to keep a reference to vec until the last reference to the LowLevelView goes out of scope. To that end, we could keep a dictionary where the keys are weak references to LowLevelViews and the values are the corresponding std::vectors. Continuing from the previous code:
import weakref
cpp_objects = {}
def vector_func2(size):
def callback(x):
del cpp_objects[x]
vec = VectorFunc(size)
llv = vec.data()
wr = weakref.ref(llv, callback)
cpp_objects[wr] = vec
return np.frombuffer(llv, dtype=np.int32)
vector_func2(5)
I think this would do the trick, but it requires LowLevelView to support weak referencing.
File "/Users/tomas/repo/oct100/python/cpycppyy_issue1.py", line 46, in <module>
vector_func2(5)
File "/Users/tomas/repo/oct100/python/cpycppyy_issue1.py", line 42, in vector_func2
wr = weakref.ref(llv, callback)
TypeError: cannot create weak reference to 'cppyy.LowLevelView' object
When building using MSVC on windows, you get an error stating that ssize_t was not defined.
Here is the whole error:
× Building wheel for CPyCppyy (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [13 lines of output]
running bdist_wheel
running build
running build_ext
building 'libcppyy' extension
creating build
creating build\temp.win32-3.10
creating build\temp.win32-3.10\Release
creating build\temp.win32-3.10\Release\src
"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\bin\HostX86\x86\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -Iinclude -IC:\Users\user\AppData\Local\Programs\Python\Python310\include -IC:\Users\user\AppData\Local\Programs\Python\Python310\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\cppwinrt" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\cppwinrt" /EHsc /Tpsrc\API.cxx /Fobuild\temp.win32-3.10\Release\src\API.obj -O2 -Zc:__cplusplus /std:c++17 /GR /EHsc- /MD
API.cxx
c:\users\user\appdata\local\temp\pip-install-__y5qbc_\cpycppyy_6c1c4c331ee3434685493fab1895fc7f\src\CPPInstance.h(82): error C2061: Syntax error: undeclared identificator ssize_t
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x86\\cl.exe' failed with exit code 2
Here's a complete reproducible example:
>>> import cppyy
>>> cppyy.include("iostream")
True
>>> cppyy.cppexec("int x = 1; std::cout << x << std::endl;")
1
True
>>> cppyy.gbl.x
1
>>> cppyy.cppexec("int x = 2; std::cout << x << std::endl;")
2
True
>>> cppyy.gbl.x
1
>>> del cppyy.gbl.x
>>> cppyy.cppexec("int x = 3; std::cout << x << std::endl;")
3
True
>>> cppyy.gbl.x
3
I would expect the 2nd eval of cppyy.gbl.x
to return 2
but it seems to have cached the value 1
until I explicitly delete the cached value.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.