Passing an array from C# to C++ issue.

Dec 2, 2013 at 12:36pm
So my problem is that, when I pass a array from C# to a dll created in C++, can catch the array values, but cant get the length of it.

in C#:
 
    [DllImport(pluginName)] public static extern int LoadData(float[] values);


in C++:
1
2
3
4
5
int Curve::LoadData(float[] values)
{
//return data values length
  return sizeof(x)/sizeof(float);
}


it always returns 1
Dec 2, 2013 at 1:21pm
Also pass the number of elements in the array.
Dec 2, 2013 at 1:25pm
In that case length would be limited, isn't it cire?
Last edited on Dec 2, 2013 at 1:25pm
Dec 2, 2013 at 1:55pm
As an alternative I am passing the number of elements at the moment. But I would like the Dll to count the number itself.
Dec 2, 2013 at 3:42pm
In C++,

int Curve::LoadData(float[] values) is entirely equivalent to int Curve::LoadData(float* values)

sizeof(values) inside Curve::LoadData will always be the size of a pointer to float. If you want to keep track of the number of elements, you must do so yourself. There is no way to extract or interpolate the size from the pointer that is fed to the function.
Dec 2, 2013 at 3:47pm
C# arrays and C++ arrays are not compatible.
C# arrays are rather what std::vector is in C++
Dec 2, 2013 at 3:57pm
hmm interesting, because Im actually placing the data into a vector after geting it from C#.
So here comes my next question, how could I pass the data straight from C# array to C++ Vector? Is it possible?,
Because at the moment Im doing it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void Curve::LoadCurve(float x[], float y[],float len)
{
    // Clear before doing anything
    values[0].clear();
    values[1].clear();
    // Place X vales to the vector
	for (int i = 0; i < len; i++)
	{
		values[0].push_back(x[i]);
	}

    // Place Y vales to the vector
	for (int i = 0; i < len; i++)
	{
		values[1].push_back(y[i]);
	}

	valuesLen = values[0].size();
}
Dec 2, 2013 at 4:13pm
the problem is that a C# array lives within what microsoft calls a 'managed' environment. That includes garbage collection. You need to get it out there before you can actually access it. Read this:

http://msdn.microsoft.com/en-us/library/z6cfh6e6.aspx
Dec 2, 2013 at 7:57pm
Okay, a little learning then... Anyway any sugestions, is something more compatible? I.E. Lists? Or something allready done and laying on the net, because I dont want to reinvent the wheel, I just want it to function as best as possible and continue with my coding.

Thanks for the article.
Topic archived. No new replies allowed.