Having problems passing a byte array from C# to managed C++  
Author Message
GJim





PostPosted: Visual C# General, Having problems passing a byte array from C# to managed C++ Top

I am really new to C# & .NET, so I apologize in advance if this is a really bone-headed question. I am debugging some C# code (written by someone else) that passes an array of bytes to a managed C++ function. The C# code calls the C++ function like:

cplusplusobject.Function(ref bytearray[0], ...);

The C++ function looks like this:

short cplusplusclass::Function(System::Byte* ptr, ...)

{

if (!ptr)

throw new ArgumentNullException(...);

}

Most of the time, this code works fine. For some reason, sometimes when the C# code is executed, the system throws a “'System.NullReferenceException” that an “object reference not set to an instance of an object.” The exception is thrown before I even step into the C++ function. I have tried changing the code to:

cplusplusobject.Function(ref bytearray, ...);

and

short cplusplusclass::Function(System::Byte ptr[], ...)

but the same thing happened.

The weird thing is that the exact same C# code will work fine if it is first invoked elsewhere first. Once it has been called from a different execution point, it will work fine from that point forward.

I have scoured over the code for some kind of initialization that may not be going on when the exception is thrown, but there really isn’t anything else to this function. It looks to me like this is either a bug in .NET or this is the wrong way to pass an array address, but since I am new I really don’t know. Does anyone have any ideas what may be causing this



Visual C#19