create new tag
view all tags

Calling C Code from IDL Modules

David Fanning has some excellent advice and useful info about calling C from IDL.


(From David Fanning):

  • All arrays which need to be passed between IDL and C must be allocated in IDL. This includes both arrays being passed from IDL to C and from C back to IDL. Sometimes this requires an initial call to the C code to return the array sizes which IDL will allocate, if the array sizes are not known to IDL beforehand.
  • Don't deallocate any arrays which were passed from IDL.
  • Don't pass strings, rather pass byte arrays. It is much simpler. Convert strings to byte arrays in IDL before or after the Call_External call.
  • Convert all output variables to the data type which C is expecting in the Call_External call.



See the attached files mandelbrot.c and mandelbrot.pro for examples of a C file called by an IDL routine.

First, compile the mandelbrot C routine as a shared library:

  • % gcc -fPIC -o mandelbrot.o -c mandelbrot.c
  • % ld -shared -o mandelbrot.dll mandelbrot.o

Second, run the mandelbrot routine from IDL:

  • % idl
  • IDL> result = mandelbrot(2.2,3.4,6.3,5.5,4,2.2,2.1)

The result can be printed as an array of mandelbrot values.

example of IDL routine

here is the IDL routine used to call the C-routine leakage_matrix. The C-routine expects as command line inputs 4 arguments : 2 integers l_user, dlm_user and 2 char[] arrays input_filename, output_filename and one optional argument /overwrite.

pro leakage_matrix_wrap,l_user,dlm_user,input_filename,output_filename,overwrite=overwrite

l   = strcompress(string(l_user),/remove_all)
dlm = strcompress(string(dlm_user),/remove_all)

if keyword_set(overwrite) then begin
   result=call_external("leakage_matrix.dll","main",' ',l,dlm,input_filename,output_filename,overwrite,/all_value)
endif else begin
   result=call_external("leakage_matrix.dll","main",' ',l,dlm,input_filename,output_filename,/all_value)


IDL passes arguments to the C-routine using argv in main. For this example all parameters are passed as IDL strings. The argv[] are then converted in the C-routine using strcpy for the filenames and strtol for the integers.

-- ElizabethAuden - 11 May 2005

Topic attachments
I Attachment History Action Size Date Who Comment
C source code filec mandelbrot.c r1 manage 0.9 K 2006-03-03 - 16:30 ElizabethAuden Mandelbrot C program
Unknown file formatpro mandelbrot.pro r1 manage 0.8 K 2006-03-03 - 16:30 ElizabethAuden Mandelbrot IDL program
Edit | Attach | Watch | Print version | History: r3 < r2 < r1 | Backlinks | Raw View | More topic actions
Topic revision: r3 - 2007-06-15 - ThierryToutain
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2019 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback