Reputation: 325
I'm working on a UWP project. I want to send an array of position data (currently I'm just sening a float array as a test) from c# to C++ (in order to render a generated mesh in DirectX on top of XAML stuff).
I tried this: Improper marshaling: C# array to a C++ unmanaged array (the accepted answer). But it doesn't work, I'm guessing I'm missing something, but I don't know what. When I try what he suggests, my compiler complains about the CInput struct declared in C++, because it's native, and so it can't be a parameter in a public function. (the function that is called from c#)
(I would have commented on that question, but I don't have that privilege yet.)
This is my code:
in C#:
public struct CInput
{
public IntPtr array;
}
public VideoView()
{
InitializeComponent();
Loaded += OnLoaded;
float[] test = new float[4];
CInput input = new CInput();
input.array = Marshal.AllocHGlobal(Marshal.SizeOf<float>() * test.Length);
Marshal.Copy(test, 0, input.array, test.Length);
D3DPanel.CreateMesh(out input, test.Length);
Marshal.FreeHGlobal(input.array);
}
in C++ (in D3DPanel.h):
struct CInput
{
float* array;
};
[Windows::Foundation::Metadata::WebHostHidden]
public ref class D3DPanel sealed : public Track3DComponent::DirectXPanelBase
{
public:
D3DPanel();
void CreateMesh(CInput points, int length);
}
Can anyone tell me what I'm doing wrong?
EDIT:
I tried the PassArray pattern, as described here, but it gives this error: "Error C4400 'const int': const/volatile qualifiers on this type are not supported"
void CreateMesh(const Array<float>^ points, int length);
And replacing "const Array^" with "Array" gives "syntax error: identifier 'Array'".
Upvotes: 1
Views: 1112
Reputation: 2030
You need to modify your code a little bit, as IntelliSense suggests, use
Platform::WriteOnlyArray<float>^
When it's "out" type, and
const Platform::Array<float>^
when it's "in" type. As C++/CX does not support "in/out" type.
I suggest you do the memory allocation in C++/CX, so in your C# code, you can pass in a array directly without worrying about Marshalling.
Upvotes: 1