将字符串数组从C#传递给C ++ Com

时间:2013-08-06 09:09:39

标签: c# com interop

我需要将一个字符串数组从C#模块传递给我的C ++ COM组件。以下是idl声明;

[id(11), helpstring("method deleteObjectsEx")] HRESULT deleteObjectsEx(
                [in] BSTR userName,
                [in] BSTR userPasswd, 
                [in] SAFEARRAY(VARIANT) varValues, 
                [in] BSTR deleteMode
                );

从C#我们使用以下代码来调用API

List<string> ObjectIDS = new List<string>();
ObjectIDS.Add(obj._ObjectId[0]);
ObjectIDS.Add(obj._ObjectId[1]);

/*Array ar = Array.CreateInstance(typeof(string), size);
ar.SetValue(obj._ObjectId[0], 0);
ar.SetValue(obj._ObjectId[1], 1);*/

mhubBridge.deleteObjectsEx(Encrypt(auth.UserName), 
                           Encrypt(auth.UserPassword), 
                           ObjectIDS.ToArray(),
                           obj._delMEthod);

在调用deleteObjectsEx API时,我得到“类型的第一次机会异常 System.Runtime.InteropServices.SafeArrayTypeMismatchException occurred in IPDWebService.DLL IPDWS::trace::(Tuesday, 06 August 2013 13:27): Exception in deleteObjectsEx:: message - Specified array was not of the expected type.

2 个答案:

答案 0 :(得分:1)

不工作

尝试使用ar数组。

mhubBridge.deleteObjectsEx(Encrypt(auth.UserName), 
                           Encrypt(auth.UserPassword), 
                           ar,
                           obj._delMEthod);

如果有效,请删除所有ObjectIDS“内容”。

或尝试:

(的工作

object[] ar = new object[] { obj._ObjectId[0], obj._ObjectId[1] };

并将其传递给deleteObjectsEx(...)

因为从技术角度来说VARIANTobject,所以SAFEARRAY(VARIANT)object[]

答案 1 :(得分:0)

试试这个:

object[] ar = new object[2];
ar [0] = obj._ObjectId[0];
ar [1] = obj._ObjectId[1];