- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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
Link Copied
3 Replies
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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!
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!

Reply
Topic Options
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page