Python dict to C struct

1,476 views
Skip to first unread message

Eric Frederich

unread,
Apr 25, 2011, 3:47:47 PM4/25/11
to cython...@googlegroups.com
Hello,

When you return a C struct from a Cython function what you get on the
Python side is a dictionary.
This is nice.

I need to now wrap functions that take C structs as input.

I am trying to create a helper file "conversions.pxd" that will do all
of these types of conversions.
I already have one that converts a Python datetime object to the 3rd
party library's date structure.
Now I need to convert this Python dictionary to this 3rd party's structure.

It works now for the int fields but I'm having trouble setting the
string fields.
In the .h file the structure has the strings defined as fixed length
character arrays.

How am I to copy a Python string to a character array inside of a struct?

Thanks,
~Eric

Eric Frederich

unread,
Apr 25, 2011, 3:56:43 PM4/25/11
to cython...@googlegroups.com
I should say that I have tried using strcpy by importing like this...
from libc.string cimport strcpy

And calling...

def convert_py_dict_to_foo_struct(py_dict, foo_struct* output):
strcpy(output.name, py_dict['name'])

And I get errors about not being able to convert a Python object to a
const_char*
When I try to just do output.name = py_dict['name'], then I get some
error about not being able to assign to l-value

Robert Bradshaw

unread,
Apr 25, 2011, 4:50:42 PM4/25/11
to cython...@googlegroups.com
On Mon, Apr 25, 2011 at 12:56 PM, Eric Frederich
<eric.fr...@gmail.com> wrote:
> I should say that I have tried using strcpy by importing like this...
> from libc.string cimport strcpy
>
> And calling...
>
> def convert_py_dict_to_foo_struct(py_dict, foo_struct* output):
>    strcpy(output.name, py_dict['name'])
>
> And I get errors about not being able to convert a Python object to a
> const_char*

Ugh... I'm not sure we should be using const_char* in these argument
declarations until we actually support const. You can do
<const_char*><char*>py_dict['name']

Or, as a workaround, just declare them yourself.

cdef extern from "string.h":
cdef char* strcpy(char*, char*)

Note that you should probably be doing strncpy, or check the (encoded)
length of the string and throwing an error, or you're risking smashing
your stack.

> When I try to just do output.name = py_dict['name'], then I get some
> error about not being able to assign to l-value

You can't re-assign what an array points to (nor, likely, would you
want to if there's an permanence of the resulting struct).

Reply all
Reply to author
Forward
0 new messages