![](/img/trans.png)
[英]How to Pass a function pointer of a CLI class to a C++ Method as argument
[英]How do I pass a C++ reference, to a pointer argument of a C function?
我只想在这里查看如何将引用传递给想要指针的函数。 我有一个代码示例如下。 在我的例子中,我将C ++引用传递给将改变我的值的C函数。
我应该在此调用中使用运算符的'&'地址:retCode = MyCFunc(&myVar)? 看来我正在引用一个引用,这在C ++中是不允许的。 然而,它编译好,似乎工作。
MainFunc()
{
int retCode = 0;
unsigned long myVar = 0;
retCode = MyCPlusPlusFunc(myVar);
// use myVars new value for some checks
...
...
}
int MyCPlusPlusFunc( unsigned long& myVar)
{
int retCode = 0;
retCode=MyCFunc( &myVar);
return retCode;
}
int MyCFunc ( unsigned long* myVar)
{
*myVar = 5;
}
我认为上面的代码很好,直到我在IBM网站上看到这个例子(他们没有使用'&'运营商地址): http : //publib.boulder.ibm.com/infocenter/zos/v1r11 /index.jsp?topic=/com.ibm.zos.r11.ceea400/ceea417020.htm
// C++ Usage
extern "C" {
int cfunc(int *);
}
main()
{
int result, y=5;
int& x=y;
result=cfunc(x); /* by reference */
if (y==6)
printf("It worked!\n");
// C Subroutine
cfunc( int *newval )
{
// receive into pointer
++(*newval);
return *newval;
}
一般来说,我知道你可以做到以下几点:
int x = 0;
int &r = x;
int *p2 = &r; //assign pointer to a reference
什么是正确的? 我应该在通话中使用运营商的地址吗?
你的用法是正确的,做&myVar
获取它的地址并传递给想要指针的函数。 取“引用”的地址与获取引用的地址相同。
你遇到的代码是错误的。 您无法将引用传递给需要指针的函数。 至少,不是为了int
。
实际上这个:
int x = 0;
int &r = x;
int *p2 = &r;
将x
的地址放入p2
,这就是你需要的。
使用&
运算符。 没有它,您尝试将int
无效转换为int*
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.