1

I want to pass a list of arrays (or a 2D array) such as [[1,2,3],[4,5,6]] from C to a Python script which computes and returns a list. What possible changes would be required to the embedding code in order to achieve this? The python script to be executed is as follows:

abc.py

import math
def xyz(size,wss):
    result=[0 for i in range(size)]
    for i in range(size):    
        wss_mag=math.sqrt(wss[i][0]*wss[i][0]+wss[i][1]*wss[i][1]+wss[i][2]*wss[i][2])
        result[i]=1/wss_mag
    return result

Here size is the number of 1D arrays in WSS (for e.g. 2 in case wss=[[1,2,3],[4,5,6]]) The question is different than the suggested duplicate in the sense it has to return back a list as a 1-D array to C.

tynn
  • 38,113
  • 8
  • 108
  • 143
suzaku
  • 11
  • 4
  • What do you mean by "list of arrays"? You can't put C arrays in a Python list. – user2357112 Aug 24 '16 at 21:39
  • I think a two dimensional array (in terms of C) (which would be like a list of lists in terms of Python) would be more appropriate. You can refer to the example I gave of the input I wanted. – suzaku Aug 25 '16 at 08:16
  • Possible duplicate of [How to Pass Two-dimensional array from C to Python](http://stackoverflow.com/questions/30330279/how-to-pass-two-dimensional-array-from-c-to-python) – DavidW Aug 25 '16 at 09:15
  • I know this isn't a perfect duplicate - they're using `std::vector` rather than 2D C array and they return tuples rather than lists - but it's pretty close and the answer is good so you should probably be able to get what you want from it. – DavidW Aug 25 '16 at 09:17
  • Thanks, yes it helped me solve my first part of the query, but how do I return a list back to C? – suzaku Aug 25 '16 at 09:55
  • I think I get it, I probably need to return a PyList object, and extract each element using PyList_GetItem macro and then, add it to an array. – suzaku Aug 25 '16 at 10:14
  • @suzaku Sorry - I didn't realise you wanted to go transfer the data both ways! The other thing you could look at are numpy arrays – DavidW Aug 25 '16 at 10:32

1 Answers1

0

I think what you want to do is to pass in some Lists, have them converted to C arrays and then back to Lists before returning to Python.

The Lists are received in C as a pointer to a PyObject, so to get the data from you'll have to use PyArg_ParseXX(YY), where XX and YY depend on what type of list object you had in Python and how you want it to be interpreted in C. This is where you would specify the shape information of the input lists and turn it into whatever shape you need for processing.

To return the arrays back to python you'll have to look at the Python-C API, which gives methods for creating and manipulating Python objects in C. As othera have suggested, using the numpy-C API is also an option with many advantages. In this case, you can use the PyArray_SimpleNew to create an array and populate it with your output.

Max
  • 301
  • 1
  • 9