简体   繁体   中英

Embedding Python in C: Passing a two dimensional array and retrieving back a list

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 eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM