将.Net ref(%)转换为原生(&)

时间:2011-06-06 09:11:36

标签: visual-c++ reference c++-cli interop mixed-mode

如何将C ++ / CLI int %tmp转换为本机C ++ int &tmp

void test(int %tmp)
{
    // here I need int &tmp2 for another pure C++ function call
}

3 个答案:

答案 0 :(得分:3)

现有的答案都没有正确处理输入/输出参数,更不用说任何高级用例了。

这适用于other_func在返回后不保留引用的所有情况:

void test(int %tmp)
{
    pin_ptr<int> pinned_tmp = &tmp;
    other_func(*pinned_tmp);
}

答案 1 :(得分:1)

试过这个,工作正常:

  //in the C++ dll
void testFunc( int& n )
{
  n = 5;
}

  //in the CLI app
[DllImport( "my.dll", EntryPoint = "?exported_name_here",
   CallingConvention = CallingConvention::StdCall )]
void TestFunc( int& );

void test( int% tmp ) 
{
  int n;
  TestFunc( n );
  tmp = n;
}

答案 2 :(得分:0)

void your_function(int *);
void your_function2(int &);

void test(int %tmp)
{
    int tmp2;
    your_function(&tmp2);
    your_function2(tmp2);
    tmp=tmp2;
}