2009年10月26日 星期一

[ActiveX] 在 ActiveX 中如何傳回 BSTR 字串?

下面是一個範例

// 從 ActiveX 傳回 BSTR 字串
// by Jing

// Usage 使用方法
BSTR getMyData(void){
    AFX_MANAGE_STATE(AfxGetStaticModuleState());
    BSTR  MyBstr=SysAllocString(L"                                                                                             ");
         myObj.getStrDATA(&MyBstr);

    return MyBstr;
}

// end of Usage

 

// ActiveX part
HRESULT STDMETHODCALLTYPE getString(BSTR* strDATA){
    // 要轉的字串
    char* CurrentData="1,0,0,50,50,20|0,0,0,0,0,-1|0,0,0,0,0,-1";


   // C string 轉成 BSTR
    int codePage = CP_UTF8;
    *strDATA=BSTRFromCStr(codePage,CurrentData);


    return NOERROR;
}

// Utility (核心轉換程式)
BSTR BSTRFromCStr(UINT codePage, LPCSTR s){
    int wideLen = MultiByteToWideChar(codePage, 0, s, -1, NULL, 0);
    if( wideLen > 0 )    {
        WCHAR* wideStr = (WCHAR*)CoTaskMemAlloc(wideLen*sizeof(WCHAR));
        if( NULL != wideStr )        {
            BSTR bstr;

            ZeroMemory(wideStr, wideLen*sizeof(WCHAR));
            MultiByteToWideChar(codePage, 0, s, -1, wideStr, wideLen);
            bstr = SysAllocStringLen(wideStr, wideLen-1);
            CoTaskMemFree(wideStr);

            return bstr;
        }
    }
    return NULL;
};