2015-09-25 40 views
1

我有一個簡單的Fortran應用程序,我試圖傳遞一個字符引用到C++ dll方法,然後讓C++方法設置引用字符串,但我不能讓它工作。這只是完整代碼的子集,因爲我甚至無法完成這個工作。通過Fortran字符串參考C++和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"; 
    } 
} 

回答

4

那麼,如果你寫:

void ReverseString3(char * buff, const char *text, int buffLen) 
    { 
     strncpy(buff,"yellow", 6); 
    } 

它將工作,你必須要初始化字符串爲 「」 護理在Fortran部分中有類似的東西:

strResult = " " 

看一看Assigning strings to arrays of characters

與已分配給該變量的buff字符串的地址「黃色」的指令buff = "yellow",離開原來的緩衝區不變。

+0

我結束了使用strncpy_s(),因爲Visual Studio說strncpy()是不安全的,但這得到了正確的路徑。謝謝。 –