2010-01-22 229 views
0

我正在使用Visual Studio 2008/.NET 3.5。我使用VS來使COM組件在.NET中可互操作。我添加了從應用程序到COM DLL的引用。 COM DLL是第三方對象 - SDK的一部分。COM指針結構

對於所有方法和事件,一切正常 - COM對象/事件被表示爲第一類.NET對象/事件。

這裏是發生了什麼事:

的掃描()方法運行。在執行結束時,會引發一個事件。

void scanner_ImageBuffer(int lStructure) 
{ 
} 

的參數 - lStructure - 根據文檔是:

ImageBuffer(int lStructure) 

描述:ImageBuffer的事件 將通知的 掃描的完成客戶端應用程序,並通過一個 結構包含作爲 掃描的一部分收集的 圖像的高度,大小和圖像緩衝區的寬度, 。客戶端應用程序有責任釋放分配給 圖像緩衝區的 內存,並釋放該結構的內存 。此事件可能不與 應用程序兼容。參數:

的int lStructure是一個32位指針 以下結構

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 
} 

這裏就是我堅持:如何 重建對象只有一個 int?


我曾嘗試:

[StructLayout(LayoutKind.Sequential)] 
struct ImageBufferDef 
{ 
    int lWidth; 
    int lHeight; 
    int lSize; 
    IntPtr pusBuffer; 
} 

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); 
    } 
} 
+0

當你調用'Marhsal.PtrToStructure()'時發生了什麼?它會拋出異常還是返回ImageBufferDef充滿垃圾? – cmw 2010-01-22 20:17:34

+0

引發異常。但是,這是工作:ImageBufferDef bufferDef = (ImageBufferDef) Marshal.PtrToStructure(ptr, typeof(ImageBufferDef)); 我該如何獲得嵌套的IntPtr pusBuffer? – Jason 2010-01-22 22:07:30

+0

如何在評論中突出顯示代碼? – Jason 2010-01-22 22:08:17

回答

0

由於

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

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

後,你可以嘗試

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

在情況下,你改變buffer數組類型,要小心繞其長度和Marshal.Copylength參數,這是因爲首先要考慮到數組元素大小即是它的一個short[] ,第二個想要數組的元素數而不是總字節數。