<p dir="ltr">On Apr 6, 2016 06:31, "Robert Kern" <<a href="mailto:robert.kern@gmail.com">robert.kern@gmail.com</a>> wrote:<br>
><br>
> On Wed, Apr 6, 2016 at 2:18 PM, Neal Becker <<a href="mailto:ndbecker2@gmail.com">ndbecker2@gmail.com</a>> wrote:<br>
> ><br>
> > I have C++ code that tries to share the mtrand state.  It unfortunately<br>
> > depends on the layout of RandomState which used to be:<br>
> ><br>
> > struct __pyx_obj_6mtrand_RandomState {<br>
> >   PyObject_HEAD<br>
> >   rk_state *internal_state;<br>
> >   PyObject *lock;<br>
> > };<br>
> ><br>
> > But with 1.11 it's:<br>
> > struct __pyx_obj_6mtrand_RandomState {<br>
> >   PyObject_HEAD<br>
> >   struct __pyx_vtabstruct_6mtrand_RandomState *__pyx_vtab;<br>
> >   rk_state *internal_state;<br>
> >   PyObject *lock;<br>
> >   PyObject *state_address;<br>
> > };<br>
> ><br>
> > So<br>
> > 1. Why the change?<br>
> > 2. How can I write portable code?<br>
><br>
> There is no C API to RandomState at this time, stable, portable or otherwise. It's all private implementation detail. If you would like a stable and portable C API for RandomState, you will need to contribute one using PyCapsules to expose the underlying rk_state* pointer.<br>
><br>
> <a href="https://docs.python.org/2.7/c-api/capsule.html">https://docs.python.org/2.7/c-api/capsule.html</a></p>
<p dir="ltr">I'm very wary about the idea of exposing the rk_state pointer at all. We could have a C API to random but my strong preference would be for something that only exposes opaque function calls that take a RandomState and return some random numbers, and getting even this right in a clean and maintainable way isn't trivial.</p>
<p dir="ltr">Obviously another option is to call one of the python methods to get an ndarray and read out its memory contents. If you can do this in a batch (fetching a bunch of numbers for each call) to amortize the additional overhead of going through python, then it might work fine. (Python overhead is not actually that much -- mostly just having to do a handful of extra allocations.)</p>
<p dir="ltr">Or, possibly the best option, one could use one of the many fine C random libraries inside your code, and if you need your code to be deterministic given a RandomState you could derive your state initialization from a single call to some RandomState method.</p>
<p dir="ltr">-n</p>