Ekim,
Are you sure you want to use a managed class for this? You posted
yesterday (btw, your system time or your newsreader posting time is off,
if you could change it so that you don't bottom-post, it would be
appreciated) regarding passing an array to C code. If you have a class in
C++ and you want to expose it to managed code, then I would say to go with
Jon's or Willy's recommendations, but I don't think that is what you have,
or want. I believe you have a piece of legacy C code that exports a
function, and you want to call it from C#.
Is this the case?
If it is, then the function header seems to indicate that you want to
copy content into a buffer. That is fine, but interop doesn't handle
C-style arrays correctly. It doesn't know how much information to marshal
back across the boundary. Because of this, you will have to marshal it
yourself. Now there are two ways you can go about this. The first is to
use unsafe code. You would declare your function like this:
[DllImport("myfunc.dll")]
private static extern unsafe int dummy(byte *array);
Then, in your code, you would call in an unsafe block, like this:
// The byte array.
byte[] bytes = new byte[5000];
// Declare an unsafe block, or you can put this on the method.
unsafe
{
// Fix the byte array.
fixed (byte *array = bytes)
{
// Make the call here, passing in the array.
int retVal = dummy(array);
}
}
What the above code does is it creates a managed array, and then fixes
the location in memory, then passes that pointer to the unmanaged
function.
Of course, you have to compile the above code with the unsafe flag
(check the project properties).
The other way to do it would be to take a block of unmanaged memory and
pass that to the function, declaring the parameter as an IntPtr, and then
copying the contents to the managed realm. If you want, I can provide an
example of that as well (it's just more tedious to type).
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
Ekim said:
hello,
I'm allocating a byte-Array in C# with byte[] byteArray = new byte[5000];
Now I want to pass this byte-Array to a managed C++-function by
reference,
so that I'm able to change the content of the byteArray and afterwards
see
the changes in C#.
(if you wanna know more details: the goal is to write the content of an
existing char-array in c++ precisely into the passed byteArray, so that
after the function has proceded the content of the byteArray in C# equals
the content of the char-Array of C++.)
So I hope you understand what I'm about to do - unfortunately, I have no
clue how to do this.
However, I appreciate any help,
by ekim