【问题标题】:Convert .Net ref (%) to native (&)将 .Net 引用 (%) 转换为本机 (&)
【发布时间】:2011-09-09 03:22:00
【问题描述】:

如何将 C++/CLI int %tmp 转换为原生 C++ int &tmp

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      刚刚试了一下,效果很好:

        //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;
      }
      

      【讨论】:

        【解决方案3】:
        void your_function(int *);
        void your_function2(int &);
        
        void test(int %tmp)
        {
            int tmp2;
            your_function(&tmp2);
            your_function2(tmp2);
            tmp=tmp2;
        }
        

        【讨论】:

        • 这几乎肯定会报错:编译器无法从 int* 转换为 int&
        • @stijn:这取决于“your_func”的签名。请参阅我更改的示例。
        猜你喜欢
        • 1970-01-01
        • 2018-03-13
        • 1970-01-01
        • 1970-01-01
        • 2011-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多