【问题标题】:Sending string[] from C# to C++ Dll 'E_UNEXPECTED' 'Catastrophic Error' on SafeArrayAccessData()在 SafeArrayAccessData() 上将字符串 [] 从 C# 发送到 C++ Dll 'E_UNEXPECTED' 'Catastrophic Error'
【发布时间】:2018-01-22 08:41:36
【问题描述】:

我有 c# 项目,我必须通过 DllImport 使用 C++ dll。 (我有c++ dll的源代码)

我正在从 c++ dll 中导入一个函数,如下所示:

    [DllImport("Example.dll", CallingConvention = CallingConvention.StdCall)]
    public static extern int SendRequest(ref string[] fields);

我在 c# 中像这样使用这个函数:

List<String> fields = new List<String>();
fields.Add("Test1");
fields.Add("Test2");
string[] fieldsArr = fields.ToArray();

int resultOfSendRequest = SendRequest(ref fieldsArr);

问题是 c++ dll 上的 SafeArrayAccessData 函数返回 'E_UNEXPECTED' 'Catastrophic Error'。

C++ 代码是这样的:

__declspec( dllexport ) int _stdcall SendRequest  (SAFEARRAY**);

int _stdcall SendRequest ( SAFEARRAY** arrayFlds)

{   
    int res = 0;
char s[1024], Info[1024];
S_FLDS flds[MAX_FLDS];
HRESULT hRes;

// which language is using thr Dll ?
BYTE* pData; 
hRes = SafeArrayAccessData  (*arrayFlds, (void**)&pData);
BYTE bufLang [] = {0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
Language = (memcmp(bufLang, pData, sizeof(bufLang)) == 0) ? CALLER_VC : CALLER_VB;
hRes = SafeArrayUnaccessData(*arrayFlds);

//...

}

编辑:好的,我解决了这个问题

 public static extern int SendRequest([MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] ref string[] fields);

现在问题出在 c++ dll 中,它在某处将字符串转换为 char*,它读取唯一的第一个字符,而不是整个字符串。

【问题讨论】:

  • 这并不奇怪。非托管代码返回 SAFEARRAY。您的 C# 不匹配。对如何 Marshall SAFEARRAY 做一些研究。
  • 好的,我解决了 SafeArrayAccessData() 上的错误。现在问题出在 c++ dll 中,它在某处将字符串转换为 char* 并读取唯一的第一个字符,而不是整个字符串。
  • 如果您有新问题,请不要在对此问题的编辑中提出。

标签: c# c++ dllimport


【解决方案1】:

编辑:好的,我通过使用解决了这个问题:

public static extern int SendRequest([MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] ref string[] fields);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 2014-02-22
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多