简体   繁体   English

如何使用 fortran-C 绑定将 fortran 字符串传递给 c++ 中的 const char*?

[英]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.我需要将编译时已知的字符串从 fortran 传递到 c++ 库。 None of the pages in my search results have involved this particular distinction.我的搜索结果中的所有页面都没有涉及这种特殊的区别。 Here is what the code looks like currently:这是当前代码的样子:

Fortran: 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++: 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:这编译得很好,但我的库需要 C++ function 如下所示:

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*?如何使它适用于 const char*?

The Fortran-C interoperability feature works with C functions, consequently the C++ function needs to be declared with C linkage ( extern "C" ). 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(*) ) (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(*) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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