C#调用ATL失败

xhubobo 2018-01-29 10:03:40
1、ATL中定义:
interface INvrProxy : IDispatch{
[id(1), helpstring("test")] HRESULT TestStruct([in] VARIANT* variantIn, [out] int* result);
};

2、实现:
struct Time
{
DWORD hour;
DWORD min;
DWORD sec;
};
STDMETHODIMP CNvrProxy::TestStruct2(VARIANT* variantIn, int* result)
{
try
{
HRESULT hr;
SAFEARRAY* psaStru = variantIn->parray;
Time *pTime = NULL;
Time time;

hr = SafeArrayAccessData(psaStru, reinterpret_cast<PVOID*>(&pTime));
time = *pTime;

hr = SafeArrayUnaccessData(psaStru);
SafeArrayDestroy(psaStru);

*result = (int)time.hour;
}
catch (...)
{
*result = -1;
}

return S_OK;
}

3、C#调用
        [StructLayoutAttribute(LayoutKind.Sequential, Pack = 1)]
struct Time
{
public uint hour;
public uint min;
public uint sec;
}
Time time;
time.hour = 9;
time.min = 31;
time.sec = 12;

int size = Marshal.SizeOf(time);
IntPtr pInput = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(time, pInput, false);

int ret = 0;
object obj = pInput;

try
{
mNvrProxy.TestStruct(ref obj, out ret);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}

运行会出现“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”的错误。
请教下C#该怎么传入结构体?谢谢
...全文
847 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
xhubobo 2018-01-30
  • 打赏
  • 举报
回复
别沉别沉
xhubobo 2018-01-29
  • 打赏
  • 举报
回复
C#调用ATL Dll传递结构体参数需要注意什么?
xhubobo 2018-01-29
  • 打赏
  • 举报
回复
现在用这种方式可以传参,但是ATL解析不对
                                    int size = Marshal.SizeOf(time);

                                    IntPtr pInput = Marshal.AllocHGlobal(size);
                                    Marshal.StructureToPtr(time, pInput, false);

                                    IntPtr pInput2 = Marshal.AllocHGlobal(size);
                                    Marshal.StructureToPtr(time, pInput2, false);

                                    IntPtr[] pInputs = new IntPtr[2] { pInput, pInput2 };

                                    int ret = 0;
                                    object obj = pInputs;

                                    try
                                    {
                                        mNvrProxy.TestStruct3(ref obj, out ret);
                                    }
                                    catch (System.Exception ex)
                                    {
                                        MessageBox.Show(ex.Message);	
                                    }

17,740

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 .NET Framework
社区管理员
  • .NET Framework社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧