0

I have a managed C++ function which returns a class array:

Managed C++ code:

public ref class Sample
{
public:
   double Open;
   double Close;
};

public ref class ManagedTest
{
  array<Sample^>^ ManagedTest::TestFunction()
  {
     //body
  }
};

TestFunction() is called in a C# application. I created same Sample Class in C# and try to get return value. But I get compilation error about conversion.

Here is my C# code:

[StructLayout(LayoutKind.Sequential, Size = 100), Serializable]
public class Sample
{
public double Open;
public double Close;
}
//No. 100 I can manage, just written a random number

Sample[] randomValues = new Sample[100]; //Array of random numbers
GCHandle handle = GCHandle.Alloc(randomValues, GCHandleType.Pinned);
var randPtr = handle.AddrOfPinnedObject();
var test = new ManagedTest();
randPtr = test.TestFunction();

How can I convert this managed C++ class array into C# one?

2
  • Can you provide your c# class Commented Aug 13, 2015 at 5:10
  • If you're able to edit the signature, see this similar question. I think the answer provides a better way to go about this: stackoverflow.com/questions/15806393/… Commented Aug 13, 2015 at 5:18

1 Answer 1

2

The C++ code defines the type returned by the function. In your C# code you've defined another type, unrelated to the type used in your C# code. You can throw away all the C# code and simply write:

var test = new ManagedTest();
var randPtr = test.TestFunction();

And that's it. If you want to be explicit about the types, then it would be:

ManagedTest test = new ManagedTest();
Sample[] randPtr = test.TestFunction();

Do note that you must throw away all the C# code in the question. In the excerpt above, Sample is the type defined in the C++ assembly.

This is the key point of interop using C++/CLI. The compiler is capable of consuming types declared in other assemblies. This is not like p/invoke where you need to define the type in both assemblies and ensure binary layouts match. With interop between C# and C++/CLI you define the types in one assembly and use them directly in the other assembly.

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

Comments

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.