come passare l'array float * al metodo C dallo script Python la cui allocazione di memoria avviene nel livello C.

Oct 12 2020

Sto cercando di chiamare i metodi C dallo script Python, il metodo C chiama il metodo C ++. Sto allocando un array all'interno del metodo getResults () usando malloc (). Ora il problema è come passare gli argomenti a float * o risultati nello script Python la cui allocazione di memoria avviene all'interno del livello C. Questo è io.c

int getResults(char* iFilename, char* iStagename, int iStateidCnt, 
    int* Stateids, int iEntityIdCount, int* iEntityids, char* iEntityType,
    char* iVariablegroup, char* ivariable, int *oRescount,
    float* oResults)
{
    int Status, i;
        EString etype(iEntityType), stagename(iStagename);
    EString vargroup(iVariablegroup);
    std::vector<ERF_INT> entity_ids;
    std::vector<ERF_INT> stateids;
    std::vector<ERF_FLOAT> results;
    _CopyIntArrayIntoVector(iStateidCnt, Stateids, stateids);
    _CopyIntArrayIntoVector(iEntityIdCount, iEntityids, entity_ids);
    CreateIoInstance(iFilename, iStagename);
    ioData pIodata = CreateIoDataInstance();
    if (iEntityIdCount <= 0)
        pIodata.setWholeSection(true);
    else
    {
        pIodata.setWholeSection(false);
        pIodata.setEntityList(entity_ids);
    }
        
    pIodata.setStateList(stateids);
    pIodata.setType(etype);
    pIodata.setVariableGroup(iVariablegroup);
    pIodata.setVariable(ivariable);
        //This is C++ method
    Status = pIo->get_results(pIodata, results);
    *oRescount = results.size();
        //allocation for oresults whose size > 2
    oResults = (float*)malloc(results.size() * sizeof(float));
    _CopyVectorIntoDoubleArray(results, oResults);
    return Status;
}

test.py

from ctypes import *
import os, sys
dll = CDLL('D:\\erf_utils_python\\erf_utils_io.dll')
dll.getresults.argtypes = (c_char_p,c_char_p,c_int,POINTER(c_int),c_int,POINTER(c_int),c_char_p,
                                  c_char_p,c_char_p,POINTER(c_int),POINTER(c_float))
dll.getresults.restype = c_int


def make_array(ctype,arr):
    return len(arr),(ctype * len(arr))(*arr)

def getresults(filename,stagename,sids,eids,entitytype,groups,variables):
    if(len(sids)>0):
       stateidcount,stateids = make_array(c_int,sids)
    if(len(eids)>0):
       entityidcount,entityid = make_array(c_int,eids)
    oresultlen = c_int()
    float_values = POINTER(c_float)
    err = dll.getresults(filename,stagename,stateidcount,stateids,entityidcount,entityid,
                                entitytype,groups,variables,byref(oresultlen), byref(float_values))
    return err,oresultlen.value, float_values

filename = b'D:\\inputfile.h5'
stagename = b"post"
stateids = [2]
stateidcount = 1
entityidcount = 1
entityid = [1]
entitytype = b"test"
variablecount = 1
variablegroup = b"testdata"
variable = b"next"

err,oreslen,ores = getresults(filename,stagename,stateids,entityid,entitytype,variablegroup,variable)

TypeError: l'argomento byref () deve essere un'istanza di ctypes, non '_ctypes.PyCPointerType' questo è l'errore che ottengo quando eseguo lo script. Sono un po 'confuso su come inviare argomenti per float * o risultati nello script.

Risposte

MarkTolonen Oct 12 2020 at 06:48

Il float* oResultsparametro viene passato per valore, quindi è impossibile restituire un puntatore allocato in quel parametro. Utilizza invece un file float** oResults.

Inoltre, float_values = POINTER(c_float)è un tipo , non un'istanza di un tipo. Quindi byref(float_values)è equivalente al C non valido &(float*). Invece, si vuole un esempio di un puntatore POINTER(c_float)()(parentesi nota) e passare che per riferimento, simile a C float *p; func(&p). Questo passerà il puntatore per indirizzo alla funzione C, che può quindi modificarlo come parametro di output.

Ecco un esempio semplificato incentrato solo sui parametri int *oRescounte float** oResults. Inoltre è necessaria una funzione per liberare l'assegnazione:

test.cpp

#include <vector>
#define API __declspec(dllexport)

extern "C" {
    API int getResults(size_t *oRescount, float** oResults) {
        std::vector<float> results {1.25,2.5,3.75,5.0}; // Simulated results
        *oRescount = results.size(); // Return size of results
        auto tmp = new float[results.size()]; // allocate
        for(size_t i = 0; i < results.size(); ++i) // copy vector to allocation
            tmp[i] = results[i];
        *oResults = tmp; // return allocation
        return 0;
    }

    API void freeResults(float* oResults) {
        delete [] oResults;
    }
}

test.py

from ctypes import *
dll = CDLL('./test')
dll.getResults.argtypes = POINTER(c_size_t),POINTER(POINTER(c_float))
dll.getResults.restype = c_int

def getresults():
    oRescount = c_size_t()         # instance to hold the returned size
    oResults = POINTER(c_float)()  # instance of a float* to hold the returned allocation.
    err = dll.getResults(byref(oRescount), byref(oResults))

    # oResults is a float* and it is possible to index past the end.
    # Make a copy into a Python list slicing to the correct size,
    # then free it so there is no memory leak.
    results = oResults[:oRescount.value]
    dll.freeResults(oResults)

    return err,results

err,ores = getresults()
print(err,ores)

Produzione:

0 [1.25, 2.5, 3.75, 5.0]
1 PascalGetreuer Oct 12 2020 at 06:37

Nel codice C ++, la firma int getResults(..., float* oResults)non è in grado di comunicare il puntatore allocato al chiamante. La linea

oResults = (float*)malloc(results.size() * sizeof(float));

imposta il oResultspuntatore localmente all'interno di getResults, senza influire sul chiamante. Al fine di produrre un puntatore, è necessario eseguire returno utilizzare un argomento puntatore a puntatore: int getResults(..., float** oResults).

Nel codice Python, non ho familiarità con i ctypes ma sembra che float_values = POINTER(c_float)sia un problema. POINTER(c_float)crea un tipo Python per un puntatore a float. Vorresti POINTER(c_float)()creare un'istanza di tale puntatore (che inizialmente è nullo).

documentazione ctypes sui puntatori: https://docs.python.org/3/library/ctypes.html#pointers