C ++编译器如何实际传递参考参数? [英] How do C++ compilers actually pass reference parameters?

查看:183
本文介绍了C ++编译器如何实际传递参考参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是由于一些混合语言编程的结果。我有一个Fortran例程我想从C ++代码调用。 Fortran通过引用传递所有的参数(除非你另有说明)。

This question came about as a result of some mixed-language programming. I had a Fortran routine I wanted to call from C++ code. Fortran passes all its parameters by reference (unless you tell it otherwise).

所以我想我会在我的C ++代码中聪明Fortran例程如下:

So I thought I'd be clever (bad start right there) in my C++ code and define the Fortran routine something like this:

extern "C" void FORTRAN_ROUTINE (unsigned & flag);

这段代码工作了一段时间,但(当然,当我需要离开)突然开始在返回呼叫。

This code worked for a while but (of course right when I needed to leave) suddenly started blowing up on a return call. Clear indication of a munged call stack.

另一位工程师来到我后面解决了这个问题,声明了 在C ++中定义的例程 as

Another engineer came behind me and fixed the problem, declaring that the routine had to be defined in C++ as

extern "C" void FORTRAN_ROUTINE (unsigned * flag);

我会接受,除了两件事。一个是,编译器不能通过引用传递引用参数,似乎反直觉,我在任何地方都找不到任何文档。另一个是,他在同一时间改变了一大堆其他代码,所以它理论上可能是另一个变化,固定任何问题是。

I'd accept that except for two things. One is that it seems rather counter-intuitive for the compiler to not pass reference parameters by reference, and I can find no documentation anywhere that says that. The other is that he changed a whole raft of other code in there at the same time, so it theoretically could have been another change that fixed whatever the issue was.

问题是,C ++如何实际传递引用参数?它可能是免费的复制,复制出小值或什么东西?换句话说,参考参数在混合语言编程中完全无用?我想知道,所以我不再犯同样的代码杀人错误。

So the question is, how does C++ actually pass reference parameters? Is it perhaps free to do copy-in, copy-out for small values or something? In other words, are reference parameters utterly useless in mixed-language programming? I'd like to know so I don't make this same code-killing mistake ever again.

推荐答案

只是为了,我相信你是对的。我使用参考传递参数给Fortran函数所有的时间。在我的经验中,使用引用或指针在Fortran-C ++接口是等效的。我试过这个使用GCC / Gfortran,和Visual Studio / Intel Visual Fortran。它可能是编译器依赖,但我认为基本上所有编译器通过指针传递实现引用。

Just to chime in, I believe you are right. I use references for passing parameters to Fortran functions all the time. In my experience, using references or pointers at the Fortran-C++ interface is equivalent. I have tried this using GCC/Gfortran, and Visual Studio/Intel Visual Fortran. It may be compiler dependent, but I think basically all compilers implement references by pointer passing.

这篇关于C ++编译器如何实际传递参考参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆