3
\$\begingroup\$

I am new to Ctypes. I am writing a piece of code that brings an array of unknown size from C to Python using Ctypes. Unknown size here mean that Python initially doesn't know the size of the array. C code has the algorithm which creates the array. Somehow after lot of trails, I managed to write code for that:

python code: sample.py

from ctypes import *
#import needed packages
import os



def main():
    a = 6;
    lib_path = os.path.join(os.path.dirname(__file__),  'Debug','{}.dll'.format("sum"))
    #print(lib_path)
    try:
        lib = cdll.LoadLibrary(lib_path)
    except Exception as e:
        raise RuntimeError("Could not   library with this path: {}. {}".format(lib_path, e))
    class truct(Structure):
        _fields_ = [("array", POINTER(c_double)),
                    ("len", c_int)]
    va = truct()
    ty = (c_double * 1 )
    va.array = ty()
    va.len = 1
    lib.sample_function.argtypes= [POINTER(truct)]
    lib.sample_function.restype = c_int
    try:
        ret = lib.sample_function(byref(va))
    except Exception as e:
        raise RuntimeError("Library call raises exception: {}".format(e)) 

C code:

typedef struct A {

    double *array;
      int a;
} A;
void sample_function2(A* structure){
    int array_local[] = { 0,0,1,1,0};
    int iter2;
    for (iter2 =0;iter2<5;iter2++){
        if(array_local[iter2]){
            structure->array[iter2] = iter2;
    }else{
      structure->array[iter2] = 0;
    }}
}

int sample_function( A* structure)
{
    int n = 5;
    int iter;
    sample_function2(structure);

    return 0;
}

This code works as expected. But is it a good practice to use this method?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.