开发者

COM pointer to struct

I'm using Visual Studio 2008/.NET 3.5. I used VS to make a COM component interoperable in .NET. I added a reference from the application to the COM DLL. The COM DLL is a 3rd party object - part of an SDK.

For all methods and events everything is working just fine - COM objects/events are represented as a first class .NET objects/events.

Here is what is happening:

The Scan() method runs. At the end of it's execution it raises an event.

void scanner_ImageBuffer(int lStructure)
{
}

The argument - lStructure - according to the documentation is:

ImageBuffer( int lStructure )

Description: The ImageBuffer event will notify the client application of the completion of a scan and pass a structure containing the width, height, size, and image buffer of the image that was collected as part of the scan. It is the responsibility of the client application to free the memory that was allocated for the image buffer and to free the memory for the structure. This event may not be compatible with Visual Basic applications. Parameters:

The int lStructure is a 32-bit pointer to the following structure

struct _ImageBufferDef
{
    int lWidth;   // size of the image width in pixels
    int lHeight;  // size of the image height in pixels
    int lSize;    // size of the image in bytes
    unsigned short* pusBuffer;  // allocated memory containing image
}

Here is where I'm stuck: How do I reconstruct the object with only a int?


I have tried:

[StructLayout(LayoutKind.Sequential)]
struct ImageBufferDef
{
    int lWidth;
    int lHeight;
    int lSize;
    IntPtr pusBuff开发者_如何转开发er;
}

void scanner_ImageBuffer( int lStructure )
{
    IntPtr ptr = new IntPtr( lStructure );

    ImageBufferDef buf = new ImageBufferDef();

    try
    {
        Marshal.PtrToStructure( ptr, buf );
    }
    catch( Exception e )
    {
        Console.WriteLine( e.Message );
    }
}


Because of

int lSize;    // size of the image in bytes
unsigned short* pusBuffer;  // allocated memory containing image

After

ImageBufferDef bufferDef = (ImageBufferDef)Marshal.PtrToStructure(ptr, typeof(ImageBufferDef));

you can try

short[] buffer = new short[bufferDef.lSize / 2];
Marshal.Copy(bufferDef.pusBuffer, buffer, 0, buffer.Length);

In case you'll change the buffer array type, be carefull about its length and the Marshal.Copy length parameter, because the first have to take into account the array element size that is 2 being it an short[], and the second wants the element count of the array instead of the total byte count.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜