如何为c ++函数创建一个c#包装器?

时间:2013-01-23 16:14:27

标签: c# c++ c

Hello作为标题说我需要创建一个包装器来在我的C#代码中使用它。但事实是我不知道C但是我的c#好多了。

C

    HRESULT ( STDMETHODCALLTYPE *Connect )( 
        ExCtrl * This,
        /* [in] */ EX_CONNECT *pConnect);

    HRESULT ( STDMETHODCALLTYPE *Disconnect )( 
        ExCtrl * This);

    HRESULT ( STDMETHODCALLTYPE *IsConnected )( 
        ExCtrl * This);

    HRESULT ( STDMETHODCALLTYPE *GetStatus )( 
        ExCtrl * This,
        /* [out] */ ExStatus **ppStatus);
HRESULT ( STDMETHODCALLTYPE *GetPreview )( 
        ExCtrl * This,
        /* [out] */ HBITMAP *phbm);

我设法写了“连接”,“断开连接”,“IsConnected”

C ++

HRESULT Connect(String^ ServerIP)
{
    IntPtr ptr = Runtime::InteropServices::Marshal::StringToBSTR(ServerIP);//
    CComBSTR bstr;                                                                                 //Converting ip string 
    bstr.Attach(static_cast<BSTR>(ptr.ToPointer()));    



    if (IsConnected())
        return E_UNEXPECTED;        // already connected

    ExCtrl *piCtrl = NULL;
    HRESULT hr = Ex_CreateController(__uuidof(ExCtrl), __uuidof(ExCtrl), (void **)&piCtrl);
    if (FAILED(hr)) return hr;

    EX_CONNECT connection = {0};                    // Connection data

    connection.appType = APP_TYPE;                      
    connection.bstrPrimaryName=CComBSTR(bstr);              // 
    connection.layerId = (int)LAYER0 + m_iLayerNum; 
    connection.masterServer = SERVER_PRIMARY;
    TIME_ZONE_INFORMATION tz;
    connection.pTz = &tz;

    hr = piCtrl->Connect(&connection);
    if (FAILED(hr)) {
        piCtrl->Release();       // connection failed - clear the controller
    } else
        m_piCtrl = piCtrl; // succefully connected

    return hr;
}


bool IsConnected()
{
    return (m_piCtrl != NULL);
}

HRESULT Disconnect()
{
    if (!IsConnected())
        return E_UNEXPECTED;        // not connected

    HRESULT hr = m_piCtrl->Disconnect();
    if (SUCCEEDED(hr)) m_piCtrl->Release();
    m_piCtrl = NULL;
    return hr;
}

问题是“GetPreview”我不知道如何将HBitmap转换为Bitmap。我试过这样:

    HRESULT GetImagePreview(BITMAP bm)
{   
    HBITMAP hB =NULL;

    tExCtrl *piCtrl = NULL;
    HRESULT hr = Ex_CreateController(__uuidof(ExCtrl), __uuidof(ExCtrl), (void **)&piCtrl);


hr = piCtrl->GetPreview(&hB);
hr = GetObject(hB, sizeof(BITMAP), &bm);
 return hr;
}

但没有运气

谢谢,

1 个答案:

答案 0 :(得分:0)

C代码看起来像是MIDL编译器生成的COM接口的一部分,因此您可以直接在C#中使用它而不需要任何包装器(只需添加对COM组件的引用)。但是,如果您选择使用C ++ / CLI包装器,则抛出异常而不是返回HRESULT。

至于你的GetImagePreview方法,你只完成了一半的工作(你甚至没有返回任何Bitmap对象)。只需谷歌“HBITMAP到位图”,你就会得到很多结果。