【问题标题】:How to pass array of bitmaps from managed C++ to unmanaged C++如何将位图数组从托管 C++ 传递到非托管 C++
【发布时间】:2013-02-09 20:50:26
【问题描述】:

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

我可以在返回IntPtr 的托管C++ 位图上调用GetHbitmap()。我应该传递一个 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++ 可以使用的类型?

【问题讨论】:

    标签: c++ arrays unmanaged managed hbitmap


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

    【讨论】:

    • 此代码在将托管位图转换为托管 C++ 中的 HBITMAP 方面非常有用。进一步的问题:我实际上是从外部非托管 C++ 代码调用此方法。因此,当我从非托管 C++ 传入 HBITMAP 数组时,我将其作为“HBITMAP* 位图”传入。
    • 然后在托管 C++ 中,我分配位图=新 HBITMAP[# of managed bitmaps]。然后我按照上面的说明分配每个元素。这一切都很好,除了当我从托管 c++ 方法中返回时:位图数组突然变为 NULL,返回到非托管代码。我假设也许我必须在托管 C++ 中以不同方式分配 HBITMAP 数组?
    猜你喜欢
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 2013-09-02
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多