0

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

我可以调用GetHbitmap()托管 C++ 位图,该位图返回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 数组吗?如果是这样,您如何将IntPtrhBmp 转换为该数组?

托管 C++ 代码运行良好,并且正确获取位图数组。但是现在当非托管 C++ 调用 GetBitmaps 方法时,我需要将这些位图返回到非托管 C++。我不知道我应该传入什么类型的变量,然后一旦我传入它,我该怎么做才能将它转换为非托管 C++ 可以使用的类型?

4

1 回答 1

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 文件和函数名称和签名等内容。您当然必须替换它们。

于 2013-02-24T18:54:19.777 回答