C ++ / cli - >调用c#dll - >调用OpenFileDialog问题 [英] C++/cli -> calling c# dll -> calling OpenFileDialog issue

查看:250
本文介绍了C ++ / cli - >调用c#dll - >调用OpenFileDialog问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将扩展写入C ++程序。我写标准的C / C ++ DLL和我使用IJW调用C#dlls。这一直工作得很好,直到我写了一个C#dll,然后又调用了OpenFileDialog和SaveFileDialog。无论何时使用ShowDialog调用,应用程序将冻结。



因此,在做一个最小工作示例我得到:
未处理的异常类型' System.Threading.ThreadStateException'发生在System.Windows.Forms.dll



其他信息:当前线程必须设置为单线程公寓(STA)模式,在OLE调用之前制作。确保您的Main函数具有标记的STAThreadAttribute。



因此,我试图在我的最小工作示例中添加主体的STAThread属性infront,并且发生此错误。


错误C2337:'STAThread':attribute not found


所以,两个问题:


  1. 如何d0我得到最低工作示例 / li>
  2. 如何让真正的应用程序工作?

(甚至可以在#pragma非托管块中添加STAThread属性)

  #pragma unmanaged 
BOOL WINAPI DllMain(HINSTANCE hDLL,DWORD dwReason,LPVOID lpReserved)
{
...
}


解决方案

t直接控制你的线程在运行的公寓 - 一个线程只能在一个公寓在一个时间,因此如果调用到你的DLL的线程已经是一些其他公寓,那么你不能改变它。 >

您是否控制调用DLL的代码?如果没有,那么我认为你能做的最好的是启动自己的线程( 可以控制它运行的公寓,通过 CoInitializeEx(NULL,COINIT_APARTMENTTHREADED))然后调用 OpenFileDialog / SaveFileDialog


I write extensions to a C++ program. I write standard C/C++ dlls and I use IJW to call C# dlls. This has always worked perfectly until I wrote and called a C# dll that in turn called an OpenFileDialog and a SaveFileDialog. Whenever either was called with ShowDialog, the app would freeze.

So in making a "Minimum Working Example" I got an: An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll

Additional information: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.

So, I tried to add the STAThread attribute infront of the main in my "Minimum Working Example" and I got this error.

error C2337: 'STAThread' : attribute not found

So, two questions:

  1. How d0 I get the "Minimum Working Example" working and
  2. How do I get the real app working?

(is it even possible to add the STAThread attribute in a #pragma unmanaged block?)

#pragma unmanaged
BOOL WINAPI DllMain (HINSTANCE hDLL, DWORD dwReason, LPVOID lpReserved)
{ 
...
}

解决方案

When you're a DLL you can't directly control the apartment your thread is running in - a thread can only be in one apartment at a time, and so if the thread that calls into your DLL is already some other apartment, then you can't change it.

Do you control the code that is calling your DLL? If not, then I think the best you can do is to start up your own thread (in which you can control the apartment it runs in, via CoInitializeEx(NULL, COINIT_APARTMENTTHREADED)) and then call OpenFileDialog/SaveFileDialog from there.

这篇关于C ++ / cli - >调用c#dll - >调用OpenFileDialog问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆