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

标签 .net visual-studio visual-c++ concurrency c++-cli

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

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.

我不太精通混合托管和非托管代码,因此可能存在我不知道的变通办法。但另一方面,也许这只是一个愚蠢的做法。如果不是因为我发现MFC不太复杂,而Form设计器又好又简单,我就只做纯C++。偏好将两者混合使用,有什么建议吗?

最佳答案

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

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

您可以按照上面的建议使用PInvoke来解决此问题,或者也可以使用指向实现惯用语的指针来解决此问题,方法是向前声明一个“pimpl”类,并将对concrt.h的依赖项隐藏到 native .cpp文件中。然后编译成一个lib并与头文件链接。

例如在.h文件中:
//forward declaration
class PImpl;

class MyClass
{
  ....
  //forward declaration is sufficient because this is a pointer
  PImpl* m_pImpl;
}

例如在您的.cpp文件中,该文件会编译为本地lib:
  #include <ppl.h>
  class PImpl
  {
   //some concrt class
   Concurrency::task_group m_tasks;
  }

关于.net - 如何将并发运行时与.NET代码混合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3558347/

相关文章:

.net - XSLT 和 T4 代码生成方法之间有什么区别?

.net - 是否可以防止控件继承其容器的视觉样式?

c# - "A call to a PInvoke function has unbalanced the stack"

c# - Executenonquery InvalidOperationException

c++ - 整数到字符串

c# - 你如何捕获迭代变量?

visual-studio - 如果在解决方案中使用项目依赖项,MSBuild 不会复制引用(DLL 文件)

c++ - 在 macOS 上的 Visual Studio 中创建 C++ 控制台应用程序

c++ - 如何使用 const 成员变量设置数组大小?

c++ - 使用 LoadLibrary 加载 dll