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?

Nipun
  • 2,217
  • 5
  • 23
  • 38
  • Can you provide your c# class – JonSquared Aug 13 '15 at 05: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: http://stackoverflow.com/questions/15806393/pinvoke-issue-with-returned-array-of-doubles – Cory Aug 13 '15 at 05:18

1 Answers1

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490