Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
Announcements
FPGA community forums and blogs on community.intel.com are migrating to the new Altera Community and are read-only. For urgent support needs during this transition, please visit the FPGA Design Resources page or contact an Altera Authorized Distributor.
29286 Discussions

returning a string from a C function

iglesu
Beginner
645 Views

Is it possible to return a string from C?
I'm trying the below to no avail

C Fortran
CHARACTER(len=30) fstr
INTERFACE
FUNCTION foo()
CHARACTER(30) :: foo
END FUNCTION
END INTERFACE

fstr=foo ()

print 10, fstr
10 format('string returned = [',a30,']')

and the C function

char * foo_() {
char *retstr;
retstr=(char *) malloc(sizeof(char)*30);
strcpy(retstr,"String returned from C");
return retstr;
}

any suggestions?

Thanks

Igor
0 Kudos
3 Replies
TimP
Honored Contributor III
645 Views

Please read your compiler document, or follow a prior example. If you don't want to use a compiler which implements new Fortran standard methods, follow an example which passes the Fortran string to and from the C in subroutine arguments.

call foo(fstr)



#include
void foo_(char *retstr, int len){
strncpy(retstr,"string",len)
...

Read the C string stuff in the ifort doc, and try to find an explanation of the implied character length argument.
I do find it difficult to get around this subject in the ifort document. Big changes are coming in a month or so. Ifort 10 should support the following way:
http://atom.princeton.edu/donev/Fortran/DLL/DLL.Forum.txt

0 Kudos
Steven_L_Intel1
Employee
645 Views
Your function foo does not return a string. It returns a pointer to a C string, quite a bit different. You could do something like this:

interface
function foo ()
integer(int_ptr_kind()) :: foo
end function foo
end interface

character(30) fstr
pointer (pstr,fstr)

pstr = foo()
i len= index(fstr,char(0))
fstr = fstr(1:ilen-1)
! Now you can use fstr
0 Kudos
iglesu
Beginner
645 Views
mmh, very, very interesting.
Most probably if we need to return a string we'll pass it by argument but thank you so much for your response .. very entlightning!
0 Kudos
Reply