COINIT_APARTMENTTHREADING 不起作用,而 MULTITHREADING 可以在我的 C# 包装类中工作
我有一个 C++ 类,它可以完成我需要它完成的任何工作,并且有一个它的包装器,以便我可以通过 C# 访问它。 C++ 类将线程类型设置为 APARTMENT THREADING,当我从另一个 C++ 类访问它时,它工作正常。如果我通过 C# 包装器运行它,则仅当 C++ 类设置为多线程时它才有效。
我尝试在调用 C++ 类之前将包装器设置为启动它自己的公寓线程,但它似乎无法成功初始化线程。当我打印 HRESULT 时,它表示一切都已成功完成。
我不知道我在这里缺少什么,如果有人可以提供帮助,我将不胜感激。 提前致谢! -亚历克斯
I have a C++ class that does whatever work I need it to do and a wrapper for it so I can access it through C#. The C++ class sets the threading type to APARTMENT THREADING and when I access it from another C++ class, it works fine. If I run it through my C# wrapper, it only works if the C++ class is set to multithreading.
I tried to set the wrapper to start it's own apartment thread before calling the C++ class but it can't seem to initiallize the thread successfully. When I print the HRESULT, it says everything completed successfully.
I don't know what I'm missing here and if anyone can help, it would be appreciated.
Thanks in advance!
-Alex
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,不起作用。类无法可靠地设置线程的单元,除非它创建线程。这里的情况肯定不是这样,CLR 已经创建了线程。并且已经调用了CoInitializeEx(),所选的公寓以后无法更改。
如果您的 C++ 代码需要单线程单元,那么 C# 代码必须提供帮助。通过将 [STAThread] 属性放在 Main() 方法上。或者在创建自己的线程时调用 Thread.SetApartmentState() 来调用您的代码。线程池线程始终是 MTA,无法更改。
顺便说一句,这是一个完全合理的期望,许多本机代码都有 STA 要求。请注意,C# 代码还必须泵送消息循环才能使 STA 工作。如果您创建 Winforms 或 WPF 应用程序,这一切都会得到解决。
Yes, doesn't work. A class cannot set the apartment of a thread reliably unless it created the thread. Which is certainly not the case here, the CLR has created the thread. And has already called CoInitializeEx(), the selected apartment cannot be changed later.
If your C++ code requires a single-threaded apartment then the C# code has to help. Either by putting the [STAThread] attribute on the Main() method. Or by calling Thread.SetApartmentState() when it creates its own Thread to call your code. A threadpool thread is always MTA, that cannot be changed.
This is an entirely reasonable expectation btw, lots of native code has STA requirements. Beware that the C# code must also pump a message loop to make the STA work. This is all taken care of if you create a Winforms or WPF app.