简体   繁体   中英

How do I pass a fortran string to const char* in c++ using fortran-C binding?

I need to pass a string known at compile time from fortran to a c++ library. None of the pages in my search results have involved this particular distinction. Here is what the code looks like currently:

Fortran:

subroutine fci_wmm_associate_variable(array_name, array_pointer)
    implicit none
    character*100, intent(in), value       :: array_name
    type (c_ptr), intent(in)        :: array_pointer
    interface
        subroutine wmm_associate_variable(name_f, pointer_f) bind (c)
            use iso_c_binding
            character (c_char), intent(in)  :: name_f
            type (c_ptr), intent(in), value :: pointer_f
        end subroutine wmm_associate_variable
    end interface
    call wmm_associate_variable(array_name, array_pointer)
end subroutine fci_wmm_associate_variable

C++:

void wmm_associate_variable(char* varname, double* var_pointer)
{
    //do stuf
}

This compiles fine, but my library needs the C++ function to look as follows:

void wmm_associate_variable(const char* varname, double* var_pointer)
{
    //do stuf
}

I get an undefined reference when this happens:

undefined reference to `wmm_associate_variable'

How do I make it work for a const char*?

The Fortran-C interoperability feature works with C functions, consequently the C++ function needs to be declared with C linkage ( extern "C" ).

(Note the Fortran declaration of the C function has the first argument as a default character kind scalar with length c_char - what you more than likely want is for it to be a c_char kind, length one assumed size array - character (KIND=c_char), intent(in):: name_f(*) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM