empty object from C

Stefan Behnel stefan_ml at behnel.de
Fri Dec 7 20:04:04 CET 2012


Eric Frederich, 07.12.2012 16:42:
> From C, I'd like to call a Python function that takes an object and sets
> some attributes on it.
> Lets say this is the function...
> 
> def foo(msg):
>     msg.bar = 123
>     msg.spam = 'eggs'
> 
> How do I create an empty object in C?
> In Python I would do something like this...
> 
> class Msg(object):
>     pass
> 
> ... and then instantiate an instance, and call the function.
> 
> msg = Msg()
> foo(msg)
> 
> I know how to create an empty dictionary and I get get by with that, but
> I'd like to create an object.

Here's some Cython code that you can call from C (after linking it in and
creating a Python interpreter at runtime):

    cdef public set_attributes(msg, int bar, char* spam):
        msg.bar = bar
        msg.spam = spam.decode('utf8')   # or whatever you use

However, how you'd use it depends on your actual C code. Personally, I'd
drop C and write all Python interaction in Cython. Makes these things way
easier.

Here are some longer examples:

https://github.com/cython/cython/tree/master/Demos/embed

https://github.com/cython/cython/tree/master/Demos/callback

Stefan





More information about the Python-list mailing list