使用指针参数(WCT)从C#调用C ++方法

时间:2015-12-01 12:42:44

标签: c# c++ pinvoke

我不熟悉从C#调用C ++方法的概念。

假设我想从C#调用C ++函数# -*- coding: utf-8 -*- class CommonParent(object): mutable_field = u'parent_replace' format_field = u'parent_format' full_pattern = u'{{to_replace}} {to_format}' @classmethod def setVariables(cls): cls.pattern = cls.full_pattern.replace(u'{{to_replace}}', cls.mutable_field) cls.result_string = cls.pattern.format( to_format=cls.format_field ) class Child1(CommonParent): mutable_field = u'child1_replace' class Child2(CommonParent): mutable_field = u'child2_replace' format_field = u'child2_format' class Result(Child1): def __init__(self): super(Result, self).setVariables() result = Result() print getattr(result, 'result_string')

https://msdn.microsoft.com/en-us/library/windows/desktop/ms679364(v=vs.85).aspx https://msdn.microsoft.com/en-us/library/windows/desktop/ms681623(v=vs.85).aspx

我已经建立了一个呼叫所依赖的其他类型的模型:

GetThreadWaitChain

如何调用GetThreadWaitChain函数?它接受指向WAITCHAIN_NODE_INFO struct ...

的指针

目前,这就是我如何调用该功能(显然它不起作用):

[DllImport("Advapi32.dll")]
public static extern void CloseThreadWaitChainSession(IntPtr WctHandle);

 [DllImport("Advapi32.dll")]
 public static extern HANDLE OpenThreadWaitChainSession(UInt32 Flags, UInt32 callback);

[DllImport("Advapi32.dll")]
        public static extern BOOL GetThreadWaitChain(
            IntPtr WctHandle,
            UInt32 Context,
            UInt32 flags,
            UInt32 ThreadId,
            WAITCHAIN_NODE_INFO NodeInfoArray,
            UInt32 IsCycle
        );

[StructLayout(LayoutKind.Sequential)]
public struct WAITCHAIN_NODE_INFO
{
    public UInt32 ObjectType;
    public UInt32 ObjectStatus;

    public struct LockObject
    {
        string ObjectName;                
        UInt64 Timeout;
        UInt32 Alertable;
    }

    public struct ThreadObject
    {
        UInt32  ProcessId;
        UInt32  ThreadId;
        UInt32  WaitTime;
        UInt32  ContextSwitches;
    }
}

我的C ++类型是否正确映射到C#类型?

1 个答案:

答案 0 :(得分:4)

GetThreadWaitChain函数原型不正确。 它应该是:

[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool GetThreadWaitChain(
    IntPtr  WctHandle,
    IntPtr Context,
    UInt32 Flags,
    int ThreadId,
    ref int NodeCount,    
    [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] 
    [In, Out] 
    WAITCHAIN_NODE_INFO[] NodeInfoArray,  
    out int IsCycle
);

首先调用时分配WAITCHAIN_NODE_INFO数组。

WAITCHAIN_NODE_INFO[] data = new WAITCHAIN_NODE_INFO[16];