如何将并发运行时与.NET代码混合使用?

Mic*_*cci 4 .net concurrency c++-cli visual-studio visual-c++

我一直在C++静态库中使用并发运行时,最近想在C++/CLI项目中使用这个库,以利用Windows窗体设计器并避免使用MFC.不幸的是,并发运行时与C++/CLI中所需的/ clr开关不兼容.我尝试在"#pragma unmanaged ... #pragma managed"指令中包含使用并发运行时的包含头文件,但是虽然过去对其他代码有用,但在这种情况下似乎不起作用.我的意思是我得到错误:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\concrt.h(27): fatal error C1189: #error :  ERROR: Concurrency Runtime is not supported when compiling /clr.
Run Code Online (Sandbox Code Playgroud)

我不是非常精通混合托管代码和非托管代码,所以有可能是我不知道的解决方法.但另一方面,也许这只是一种愚蠢的方法.如果不是因为我发现MFC不可能复杂,并且表单设计器如此美观和简单,我只会做纯C++.喜欢混合两者,有什么建议吗?

Ric*_*ick 7

使用C++/CLI中的ConcRT在concrt.h中通过以下语句明确禁用,因为它不受官方支持...

#if defined(_M_CEE)
   #error ERROR: Concurrency Runtime is not supported when compiling /clr.
#endif
Run Code Online (Sandbox Code Playgroud)

你可以使用PInvoke解决这个问题,如上所述,或者你也可以使用指向实现习惯用法的指针通过向前声明一个'pimpl'类来解决这个问题,并将对concrt.h的依赖隐藏到本机.cpp文件中你可以然后编译成一个lib并与头文件链接.

例如在.h文件中:

//forward declaration
class PImpl;

class MyClass
{
  ....
  //forward declaration is sufficient because this is a pointer
  PImpl* m_pImpl;
}
Run Code Online (Sandbox Code Playgroud)

例如,在.cpp文件中编译成本机库:

  #include <ppl.h>
  class PImpl
  {
   //some concrt class
   Concurrency::task_group m_tasks;
  }
Run Code Online (Sandbox Code Playgroud)