gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:35:05 24 4
gpt4 key购买 nike

我对从 C# 调用 C++ 方法这个概念还很陌生。

假设我想从 C# 调用 C++ 函数 GetThreadWaitChain:

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

我还构建了调用所依赖的其他类型的模型:

[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;
}
}

如何调用 GetThreadWaitChain 函数?它接受指向 WAITCHAIN_NODE_INFO 结构的指针...

目前,这就是我想出的调用函数的方式(显然它不起作用):

 void CollectWaitInformation(int threadId)
{
var wctHandle = OpenThreadWaitChainSession(0, 0);
WAITCHAIN_NODE_INFO info = new WAITCHAIN_NODE_INFO();
var result = GetThreadWaitChain(wctHandle, 0,
GetThreadWaitChainFlags.WCT_OUT_OF_PROC_COM_FLAG, threadID, info , 0);
}

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

最佳答案

GetThreadWaitChain 函数原型(prototype)不正确。应该是:

[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];

关于c# - 使用指针参数 (WCT) 从 C# 调用 C++ 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34020727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com