2

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. As you said - it works fine now. Time for me to crack a book. :?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.