Working with C object of python object (pycairo,ctypes)

A

AngelBlaZe

Can you access the c object of a python object directly? Can this be
done in ctypes or directly throught python functions without reverting
to forking the python module?

scanario:
I have pyctx object that i get in python like this:

pyctx = cairo.Context(surface)

defined in the python extension this:

typedef struct {
PyObject_HEAD
cairo_t *ctx;
PyObject *base; /* base object used to create context, or NULL */
} PycairoContext;

PyObject *
PycairoContext_FromContext(cairo_t *ctx, PyTypeObject *type, PyObject
*base)
{
PyObject *o;

assert (ctx != NULL);

if (Pycairo_Check_Status (cairo_status (ctx))) {
cairo_destroy (ctx);
return NULL;
}

if (type == NULL)
type = &PycairoContext_Type;
o = PycairoContext_Type.tp_alloc (type, 0);
if (o) {
((PycairoContext *)o)->ctx = ctx;
Py_XINCREF(base);
((PycairoContext *)o)->base = base;
} else {
cairo_destroy (ctx);
}
return o;
}

Now my question is:
Is there any way to access/get a pointer to PycairoContext->ctx from
python object (pyctx)?

A long shot i know :)
 
A

AngelBlaZe

Solved my own problem :)
For future reference here is the solution:

class PycairoContext(Structure):
_fields_ = [("PyObject_HEAD", c_byte * object.__basicsize__),
("ctx", c_void_p),
("base", c_void_p)]


z = PycairoContext.from_address(id(ctx))
print z.ctx

where ctx is the python object
and PycairoContext is the C object of ctx


Full Code : ( simple rsvg / librsvg ctypes wrapper )
------------------------------------------
def WebColour(sCol):
#print sCol
ic = [int(sCol[i:i+2], 16)/255.0 for i in range(1, 7, 2)]
#print ic
return ic

from ctypes import *

l=CDLL('librsvg-2-2.dll')
g=CDLL('libgobject-2.0-0.dll')
print g.g_type_init()


import cairo

WIDTH, HEIGHT = 800, 800

# Setup Cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
ctx = cairo.Context(surface)



error=''
handle1 = l.rsvg_handle_new_from_file('test.svg',error)
print error
print handle1

class PycairoContext(Structure):
_fields_ = [("PyObject_HEAD", c_byte * object.__basicsize__),
("ctx", c_void_p),
("base", c_void_p)]


z = PycairoContext.from_address(id(ctx))
print z.ctx

print '>>',l.rsvg_handle_render_cairo(handle1, z.ctx)


#add some cairo stuff on top
bg = WebColour('#FFFFFF')
ctx.set_source_rgb(bg[0],bg[1],bg[2])
# Set thickness of brush
ctx.set_line_width(15)

# Draw out the triangle using absolute coordinates
ctx.move_to(200, 100)
ctx.line_to(300, 300)
ctx.rel_line_to(-200, 0)
ctx.close_path()

# Apply the ink
ctx.stroke()

surface.write_to_png("test.png")
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,808
Messages
2,569,686
Members
45,454
Latest member
FionaValli

Latest Threads

Top