Re: [cython-users] How to convert a C array to a python object?

1,190 views
Skip to first unread message

Stefan Behnel

unread,
Sep 30, 2012, 1:12:00 AM9/30/12
to cython...@googlegroups.com
JBT, 29.09.2012 22:25:
> When I compile the code, cython issues this error message:
> ------------------------------------------------------------
> ...
> if dataType == CDF_REAL8:
> dblEntry = <double *>malloc(nElements * sizeof(double))
> status = CDFlib(
> GET_, gENTRY_DATA_, dblEntry,
> NULL_)
> entryData.append(dblEntry)
> ^
> ------------------------------------------------------------
>
> cdflib.pyx:149:37: Cannot convert 'double *' to Python object
>
> I vaguely remember reading something about converting a double array to a
> python object, but I can't find it any more. Can anyone help me, please?

Well, it's impossible for Cython to know the length of that array -
actually, it doesn't even know that it is an array, all it sees is a
pointer to a double.

You can use a list comprehension:

entryData.append([ d for d in dblEntry[:nElements] ])

I don't think this works:

entryData.append(dblEntry[:nElements])

although I wouldn't mind making it do the same thing as the list
comprehension above.

Stefan

Chris Barker

unread,
Sep 30, 2012, 2:01:13 PM9/30/12
to cython...@googlegroups.com
On Sat, Sep 29, 2012 at 1:25 PM, JBT <jianb...@gmail.com> wrote:
> Hi,
>
> I am using NASA CDF C library to extract data from .cdf files in cython. Now
> I am stuck in a type conversion problem.

When you want to convert a C array (or any C datatype, really), you
first need to ask what an appropriate Python data type should be to
hold that data.

In the case of a C array, I'd say a numpy array makes much more sense
than a list or tuple, or....An array.array would be a second choice,
if you don't want external dependencies, but I"d guess a huge
fraction of folks wanting to work with CDF are using numpy anyway (or
should be).

To wrap a numpy array around a C array, you cana create one, then
either pass the pointer in, or do a memcpy to copy the data it,
depending on whether you want Python/numpy to be responsible for
managing the memory.

See this thread for a discussion of various methods:

https://groups.google.com/forum/?fromgroups=#!topic/cython-users/2ANAMUHfOYw

-Chris



--

Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception

Chris....@noaa.gov
Reply all
Reply to author
Forward
0 new messages