2013-02-24 76 views
0

我目前在托管C++代码中有一个System::Drawing::Bitmaps数组。我希望能够从非托管(本地)C++调用托管C++中的方法。问题是如何将数组传回非托管C++?如何将托管C++位图阵列传递给非托管C++

我可以在托管的C++位图上调用GetHbitmap(),它返回IntPtr。我应该传递一组IntPtrs吗?不太确定最好的方法来做到这一点。所以要清楚,我有这样的:

托管C++方法:

void GetBitmaps(<????>* bitmaps) 
{ 
    //Calling into C# to get the bitmaps 

    array<System::Drawing::Bitmap^>^ bmp=ct->DataGetBitmaps(gcnew String(SessionID)); 
    for(int i=0;i<bmp.Length;i++) 
    { 
     System::Drawing::Bitmap^ bm=(System::Drawing::Bitmap^)bmp.GetValue(i); 
     IntPtr hBmp=bm->GetHbitmap(); 
    } 

    //So now how to I convert the hBmp to an array value that I can then pass back to unmanaged C++(hence the <????> question for the type) 
} 

是HBITMAPS的阵列?如果是这样,你怎么能将IntPtr hBmp转换为该阵列?

托管的C++代码工作得很好,并且正确地获取位图数组。但是现在当非托管C++调用GetBitmaps方法时,我需要将这些位图返回到非托管C++。我不知道应该传入哪种类型的变量,然后一旦将它传入,我该如何将它转换为非托管C++可以使用的类型?

回答

1

您一定需要创建一个非托管数组来调用您的本机代码。之后你还必须照顾正确的清理。所以基本的代码应该是这样的:

#include "stdafx.h" 
#include <windows.h> 
#pragma comment(lib, "gdi32.lib") 
#pragma managed(push, off) 
#include <yourunmanagedcode.h> 
#pragma managed(pop) 

using namespace System; 
using namespace System::Drawing; 
using namespace YourManagedCode; 

    void SetBitmaps(const wchar_t* SessionID, CSharpSomething^ ct) 
    { 
     array<Bitmap^>^ bitmaps = ct->DataGetBitmaps(gcnew String(SessionID)); 
     HBITMAP* array = new HBITMAP[bitmaps->Length]; 
     try { 
      for (int i = 0; i < bitmaps->Length; i++) { 
       array[i] = (HBITMAP)bitmaps[i]->GetHbitmap().ToPointer(); 
      } 
      // Call native method 
      NativeDoSomething(array, bitmaps->Length); 
     } 
     finally { 
      // Clean up the array after the call 
      for (int i = 0; i < bitmaps->Length; i++) DeleteObject(array[i]); 
      delete[] array; 
     } 
    } 

有没有在你的问题几乎足够的信息,使这个准确的,我不得不使用占位名字之类的C#类的名称和命名空间与本土代码.h文件和函数名称和签名。你当然必须替换它们。

+0

就代码托管C++中的托管位图转换为HBITMAP而言,此代码非常有用。进一步的问题:我实际上是从外部非托管C++代码调用此方法。所以当我从非托管C++传入HBITMAP数组时,我将它作为“HBITMAP *位图”传入。 – user1059993 2013-02-25 02:22:41

+0

然后在托管的C++ I中分配位图=新的HBITMAP [托管位图的数量]。然后我按照上面的指示分配每个元素。这一切工作正常,除非当我回到托管C++方法时:位图数组突然变为空,返回到非托管代码。我假设也许我必须在托管C++中分配不同的HBITMAP数组? – user1059993 2013-02-25 02:25:09

相关问题