How to pass a SAFEARRAY from C# to COM?

筅森魡賤 提交于 2019-12-12 08:14:22

问题


I have an ATL COM Server, where the method for the interface is

CVivsBasic::UpdateSwitchPlan(BSTR plan_name, SAFEARRAY* plan)

And the IDL for this function looks like

typedef struct  
{   
    LONG time_to_play;
    BSTR ecportid;
} SwitchPlanItem;
HRESULT UpdateSwitchPlan([in] BSTR plan_name, [in] SAFEARRAY(SwitchPlanItem) plan) ;    

I tried to call it from C# like this:

        internal void UpdateSwitch(string plan_name, string ecportid)
    {
        SwitchPlanItem sp1;
        sp1.time_to_play = 33;
        sp1.ecportid = ecportid;

        SwitchPlanItem sp2;
        sp2.time_to_play = 33;
        sp2.ecportid = ecportid;

        SwitchPlanItem[] sps = { sp1, sp2 };

        sdk.UpdateSwitchPlan(plan_name, sps);
    }

But it crash. What is the correct way to pass a SAFEARRAY from C# to COM?


回答1:


I think the problem here is that you're using a SAFEARRAY of user defined types (UDT), SAFEARRAYs of VARIANT, BSTR and IUnknown work out of the box but for UDTs you need to help the marshaller along. See this article in MSDN regarding Passing Safearray of UDTs.




回答2:


I think the answer to this question is similar to this one: COM - [in] parameter as SAFEARRAY(STRUCT)

Basically, the C# client that is using an interface where SAFEARRAY(STRUCT) are passed in, has to define Embed Interop Types = False on the imported COM server reference properties.



来源:https://stackoverflow.com/questions/1425107/how-to-pass-a-safearray-from-c-sharp-to-com

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!