calling C++/CLI from C# with out parameter

十年热恋 提交于 2019-12-11 03:09:47

问题


Need some references to better understand the out parameter (and the '%' operator used) when interfacing C# with C++/CLI. Using VS2012 and this msdn reference:msdn ref

C++ DLL code compiled with /clr

#pragma once
using namespace System;

namespace MsdnSampleDLL {

    public ref class Class1
    {
    public:
        void TestOutString([Runtime::InteropServices::Out] String^ %s) 
        {
            s = "just a string";
        }
        void TestOutByte([Runtime::InteropServices::Out] Byte^ %b) 
        {
            b = (Byte)13;
        }
    };
}

And the C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using MsdnSampleDLL;
namespace MsdnSampleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 cls = new Class1();
            string str;
            cls.TestOutString(out str);

            System.Console.WriteLine(str);

            Byte aByte = (Byte)3;
            cls.TestOutByte(out aByte);            
        }
    }
}

The string portion of this code (copied from msdn) works fine. But when I tried to expand on the idea with passing a Byte to be filled in - I got the following error from compiling the C#

Argument 1: cannot convert from 'out byte' to 'out System.ValueType'

So obviously I'm just not "getting it" from the msdn docs. I'd appreciate links to better documentation to explain this.


回答1:


The problem is in your C++/CLI declaration:

void TestOutByte([Runtime::InteropServices::Out] Byte^ %b) 

System::Byte is a value type, not a reference type, therefore it doesn't get the ^. A reference to a value type isn't something that can be represented in C#, so a reference to ValueType is used instead.

Get rid of the ^ on the Byte, and it'll work fine.



来源:https://stackoverflow.com/questions/28610868/calling-c-cli-from-c-sharp-with-out-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!