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

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
Also pass the number of elements in the array.
In that case length would be limited, isn't it cire?
Last edited on
As an alternative I am passing the number of elements at the moment. But I would like the Dll to count the number itself.
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.
C# arrays and C++ arrays are not compatible.
C# arrays are rather what std::vector is in C++
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();
}
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
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.