[Pyrex] Re: Wrapping _randommodule.c
Robert Kern
robert.kern at gmail.com
Mon Oct 31 18:33:11 CET 2005
Simon Frost wrote:
> Dear Pyrex List,
>
> I'd like to be able to access the internals of the RandomType object, as
> defined in _randommodule.c, so I can generate random numbers within C
> code. It's defined as follows:
>
> typedef struct {
> PyObject_HEAD
> unsigned long state[N];
> int index;
> } RandomObject;
>
> Random numbers are then generated using:
>
> static PyObject * random_random(RandomObject *self);
>
> What I would like to do is to generate a random number class generated
> within Python
>
>>> import random
>>> rng=random.Random(1)
>
> and then pass it to functions in Pyrex.
>
> My questions are:
> 1. How do I link against _randommodule?
You don't. It doesn't expose a C API; you can't call random_random()
from other extension modules.
> 2. RandomObject is a struct containing a PyObject, which Pyrex doesn't
> like. What's the usual workaround (except pass)?
No, it *is* a PyObject. You don't put PyObject_HEAD in the Pyrex struct
definition. You would do something like the following, I believe:
ctypedef class _random.Random [object RandomObject]:
cdef unsigned long state[624]
cdef int index
I recently added Mersenne Twister PRNG support for scipy_core. Since I
couldn't use _random's implementation, I used a small implementation
called RandomKit. You can see the code here:
http://svn.scipy.org/svn/scipy_core/branches/newcore/scipy/corelib/mtrand/
You can sync it with a random.Random() instance, if you must, by
getting/setting the state.
--
Robert Kern
rkern at ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
More information about the Pyrex
mailing list