Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error in Python trying to create a list of a certain length after a call to Fortran to get the length

I have a piece of Python code which needs to call Fortran to get the length of a list Python needs to create (so that it can pass that list of the correct size back to Fortran later).

Here is the code:

# get size of x
n = ct.c_int(0)
fs(ct.byref(n)) # fs is a Fortran subroutine which returns the length
print('n: ',n)
x = [0]*n
print('x: ',x)

However Python complains:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    x = [0]*n
TypeError: can't multiply sequence by non-int of type 'c_long'

If I change the initialization of n to n=0, the byref call on the next line fails with:

    fs(ct.byref(n))
TypeError: byref() argument must be a ctypes instance, not 'int'

How do I create a list of length n (obtained from Fortran)?

>Solution :

You can try explicit conversion of this type to int x = [0]*int(n)

if that doesn’t work, try x = [0]*n.value, refer: How to convert ctypes' c_long to Python's int?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading