Home     |     .Net Programming    |     cSharp Home    |     Sql Server Home    |     Javascript / Client Side Development     |     Ajax Programming

Ruby on Rails Development     |     Perl Programming     |     C Programming Language     |     C++ Programming     |     IT Jobs

Python Programming Language     |     Laptop Suggestions?    |     TCL Scripting     |     Fortran Programming     |     Scheme Programming Language

Cervo Technologies
The Right Source to Outsource

MS Dynamics CRM 3.0

C# Programming

A hint on marshalling a byte array into a void* pointer

I have to pass a byte array as an input parameter to a function in a
propertary dll.
The c++ signature of the original function is the following:

---------- C++ ----------

        int ncWrite(unsigned long ObjHandle, unsigned long DataSize, void*

---------- end C++ ----------

>From C# I have defined this function as:

---------- C# ----------

        unsafe static extern int ncWrite(uint ObjHandle, uint DataSize,
IntPtr DataPtr);

---------- end C# ----------

And I use it as:

---------- C# ----------

        byte[] DataWrite = {0x23, 0x23, 0x30, 0x03, 0x78, 0xEC, 0xFF, 0xFF };
        int myStatus;

        IntPtr ptr = Marshal.AllocHGlobal(8);
        Marshal.Copy(DataWrite, 0, ptr, 8);
        myStatus = ncWrite(WriteAddress, 8 , ptr);

---------- end C# ----------

This works, but having to handle unmanaged code I''m worried by memory
leaks (this function is called thousdands of times per minute).
Is it the usage correct? Have I choosen the right Marshal methods
(Marshal.AllocHGlobal, Marshal.Copy, Marshal.FreeHGlobal)?

Thank you very much

"Beorne" <matteo@gmail.com> schrieb im Newsbeitrag

This seems to be OK. You should add a try/finally to get sure the memory
gets cleared in case of an exception.

IntPtr ptr = Marshal.AllocHGlobal(8);
    Marshal.Copy(DataWrite, 0, ptr, 8);
    myStatus = ncWrite(WriteAddress, 8, ptr);






On 30 Mag, 10:39, "Christof Nordiek" <c@nospam.de> wrote:

You don't really need to manually marshal the data. Change your C#
declaration to:

unsafe static extern int ncWrite(uint ObjHandle, uint DataSize, byte[]

and then just pass in DataWrite as is. The runtime marshaller will pin your
array and then pass in a pointer to the unmanaged function.

"Beorne" <matteo@gmail.com> wrote in message


Add to del.icio.us | Digg this | Stumble it | Powered by Megasolutions Inc