我有一个简单的 Fortran 应用程序,我试图将字符引用传递给 C++ dll 方法,然后让 C++ 方法设置引用字符串,但我无法让它工作。这只是完整代码的一部分,因为我什至无法让它工作。
Fortran 代码
program FortranConsoleExample
implicit none
interface
!!!
subroutine reverseString(str_out, str_in, str_in_len) bind(C, name="ReverseString3")
USE, INTRINSIC :: ISO_C_BINDING
integer(C_INT), VALUE, INTENT(IN) :: str_in_len
character, dimension(*), intent(IN) :: str_in
character(kind=C_CHAR), dimension(512), intent(out) :: str_out
end subroutine reverseString
end interface
! Variables
character*512 :: strResult
call reverseString(strResult, "tacobell", len(strResult))
print *, strResult
end program FortranConsoleExample
C++代码
extern "C"
{
__declspec(dllexport) void __cdecl ReverseString3(char * buff, const char *text, int buffLen)
{
buff = "yellow";
}
}
最佳答案
好吧,如果你写:
void ReverseString3(char * buff, const char *text, int buffLen)
{
strncpy(buff,"yellow", 6);
}
它将起作用,您必须注意将 Fortran 部分中的字符串初始化为“”,例如:
strResult = " "
看看Assigning strings to arrays of characters
使用指令 buff = "yellow"
,您已将字符串“yellow”的地址分配给变量 buff,而原始缓冲区保持不变。
关于c++ - 将 Fortran 字符串引用传递给 C++ 和 C++ 设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32784463/