C++/C# interop causes OleInitialize (STA) to fail?

Is there something about C++ / C# interop that initializes the threading 
model to MTA so that OleInitialize will fail?

I have a mostly C++ app that calls a single C# class DLL. Only one source 
file in the C++ app is compiled as managed (with /clr) – the single file in 
which only one of the many functions creates a class object from the C# DLL 
and invokes its methods (to decode an XML file the easy way).

During normal execution my code eventually creates an instance of an 
MSFlexGrid ocx object (a grid control with column and row headers), which in 
turn calls AfxOleInit and therefore OleInitialize. Works fine in normal 
execution. I believe OleInitialize is by default STA. 

By “normal” execution I mean the situation when I do not execute any code in 
that single C++ file that calls into the C# DLL. If, however, I call 
functions in that C++ file (even if they do not call the only function that 
invokes C#), then when I create the MSFlexGrid object the internal call to 
OleInitialize fails with the Trace message “Warning: OleInitialize returned 
scode = RPC_E_CHANGED_MODE ($80010106)”.  

From the help files it sounds like OleInitialize expects to be run in STA 
mode, and the error message means “A previous call to CoInitializeEx 
specified the concurrency model for this apartment as multithread apartment 
(MTA)”. I tried putting breakpoints on every bit of MFC / ATL source code 
that calls OleInitialize or CoInitialize to see if I could find the offender, 
but nothing trapped.

If I create the MSFlexGrid before invoking C#, all is fine, and if I call 
OleInitialize at the very beginning of my app all is fine. But I’m worried 
there is a threading disaster waiting to happen.

What’s the deal?

0
9/29/2005 3:26:02 PM
vc.mfc 33608 articles. 0 followers. Follow

7 Replies
1431 Views

Similar Articles

[PageSpeed] 36

Take a look at the Paul Dilascia's CSTAThread class here

            http://msdn.microsoft.com/msdnmag/issues/05/03/CATWork/
-- 
Cheers
Check Abdoul [VC++ MVP]
-----------------------------------

"Bill Cumming" <BillCumming@discussions.microsoft.com> wrote in message
news:280D4F6A-0BB0-4841-8AE1-51E7117222AE@microsoft.com...
> Is there something about C++ / C# interop that initializes the threading
> model to MTA so that OleInitialize will fail?
>
> I have a mostly C++ app that calls a single C# class DLL. Only one source
> file in the C++ app is compiled as managed (with /clr) - the single file
in
> which only one of the many functions creates a class object from the C#
DLL
> and invokes its methods (to decode an XML file the easy way).
>
> During normal execution my code eventually creates an instance of an
> MSFlexGrid ocx object (a grid control with column and row headers), which
in
> turn calls AfxOleInit and therefore OleInitialize. Works fine in normal
> execution. I believe OleInitialize is by default STA.
>
> By "normal" execution I mean the situation when I do not execute any code
in
> that single C++ file that calls into the C# DLL. If, however, I call
> functions in that C++ file (even if they do not call the only function
that
> invokes C#), then when I create the MSFlexGrid object the internal call to
> OleInitialize fails with the Trace message "Warning: OleInitialize
returned
> scode = RPC_E_CHANGED_MODE ($80010106)".
>
> From the help files it sounds like OleInitialize expects to be run in STA
> mode, and the error message means "A previous call to CoInitializeEx
> specified the concurrency model for this apartment as multithread
apartment
> (MTA)". I tried putting breakpoints on every bit of MFC / ATL source code
> that calls OleInitialize or CoInitialize to see if I could find the
offender,
> but nothing trapped.
>
> If I create the MSFlexGrid before invoking C#, all is fine, and if I call
> OleInitialize at the very beginning of my app all is fine. But I'm worried
> there is a threading disaster waiting to happen.
>
> What's the deal?
>


0
CheckAbdoul
9/29/2005 3:47:41 PM
That's roughly what I tried, and it does indeed solve the problem to call 
CoInitialize (or OleInitialize) before the Framework calls it with 
COINIT_MULTITHREADED.

Two questions:
1) My original question: is this a threading disaster waiting to happen by 
setting the mode to STA? Are there other conflicts I should be aware of?

2) By setting the mode to STA will that disable the garbage collector?

Thanks!

"CheckAbdoul" wrote:

> Take a look at the Paul Dilascia's CSTAThread class here
> 
>             http://msdn.microsoft.com/msdnmag/issues/05/03/CATWork/
> -- 
> Cheers
> Check Abdoul [VC++ MVP]
> -----------------------------------
> 

0
9/29/2005 4:23:01 PM
Hi,

> That's roughly what I tried, and it does indeed solve the problem to call 
> CoInitialize (or OleInitialize) before the Framework calls it with 
> COINIT_MULTITHREADED.
> 
> Two questions:
> 1) My original question: is this a threading disaster waiting to happen by 
> setting the mode to STA? Are there other conflicts I should be aware of?

Definitely not. The runtime simply defaults to MTA, if it
detects that CoInitialize was not called before, and
if the main entry point of an executable assembly doesn't
apply the STAThreadAttribute.

> 2) By setting the mode to STA will that disable the garbage collector?

No.

Rob

> 
> Thanks!
> 
> "CheckAbdoul" wrote:
> 
> 
>>Take a look at the Paul Dilascia's CSTAThread class here
>>
>>            http://msdn.microsoft.com/msdnmag/issues/05/03/CATWork/
>>-- 
>>Cheers
>>Check Abdoul [VC++ MVP]
>>-----------------------------------
>>
> 
> 
0
robertj (3)
9/29/2005 11:24:07 PM
Bill,

> Is there something about C++ / C# interop that initializes the threading
> model to MTA so that OleInitialize will fail?

Well, by default the CLR will initialize managed threads into the MTA. In C# 
or VB, you can usually prevent this for the application's main thread by 
tagging the entry point method with the [STAThread] attribute. 
Unfortunately, this doesn't work reliably in Managed C++ because the main() 
function is not actually the application's entry point (the actual one is in 
the CRT).

Sounds like this might help:
http://support.microsoft.com/kb/824480


-- 
Tomas Restrepo
tomasr@mvps.org
http://www.winterdom.com/ 


0
tomasr (4)
9/30/2005 5:09:37 AM

Thanks for the info! I was getting nervous.
0
9/30/2005 1:47:03 PM
While the article applies directly to the issue I have, the proposed 
solution is more appropriate for a command line app since you can more easily 
get at the startup routine. But the article accurately describes my situation.

I merely added a call to OleInitialize(NULL) very early on in my app before 
any calls to the Framework (which initializes COM as MTA), and that seems to 
have solved my problem.

Thanks for your help!
0
9/30/2005 2:00:02 PM
Bill,
>
> While the article applies directly to the issue I have, the proposed
> solution is more appropriate for a command line app since you can more 
> easily
> get at the startup routine. But the article accurately describes my 
> situation.
>
> I merely added a call to OleInitialize(NULL) very early on in my app 
> before
> any calls to the Framework (which initializes COM as MTA), and that seems 
> to
> have solved my problem.

Glad to know. If your app does not have a managed entry point, then that 
probably works. The problem with this, if there's a managed entry point, is 
that you're not guaranteed it will work because you can't predict what the 
runtime did before you...


-- 
Tomas Restrepo
tomasr@mvps.org
http://www.winterdom.com/ 


0
tomasr (4)
9/30/2005 2:42:46 PM
Reply:

Similar Artilces:

How to build a project in Visual C++.net developed in Visual C++ 6
Hi, I am Nageshwar. I have developed a project in VC++ 6.0 and OpenGL. I have installed VC++.net in my system. When I compile and build the same code in VC++.net environment, I am getting errors. I have used fstream.h to read and write to files. But this header file is showing errors in VC++.net. I have used iostrea.h header. This is also showing erros. I think I need to use a different version of headers. Please suggest me how to recover from these errors. Which header file I have use instead of fstream.h header? etc., Thanks for all who help me.. Awaiting an early response, Nageshwar ...

Autorefresh Fails on Open
I set up a simple pivot table that gets its data from CSV file which is set to import automatically upon opening. I worked fine for two days then stopped... I re-created another external data import, same opens to refresh automatically on open. It works once or twice then stops. HELP! ...

C: Drive documents and setting expansion
Whenever I, Right Click Start then click "Explore", I get an expansion of the my user ID folders. Now, I rarely us "Documents and Settings" and would like to have it expand differently. What do I need to change so that can happen?? Thanks.. Bruce A. Julseth wrote: > Whenever I, Right Click Start then click "Explore", I get an > expansion of the my user ID folders. Now, I rarely us "Documents and > Settings" and would like to have it expand differently. > > What do I need to change so that can happen?? 1. You could ...

OLE DB Provider failing
Hi All, I am running Windows Server 2003 x32 SP2 with SQL Server 2005. I am being told by a vendor that is trying to install a piece of software that my "OLE DB Provider for SQL Server" is failing. And, that this is part of MDAC. How do I reinstall this stuff? Many thanks, -T > I am being told by a vendor that is trying to install > a piece of software that my "OLE DB Provider for SQL > Server" is failing. And, that this is part of MDAC. > > How do I reinstall this stuff? What exactly does the vendor mean by "failing"? MD...

MSMoney 2005 Failed Update
Hi, In the past i was able to update my Account's transactions using MSMoney 2005. Now i'm getting the message "Update not completed". I don't really know what the problem is, but i'm able to get the response from the OFXServer to MSMoney2005. When i analyse this response with Microsoft's OFXAnalyser i get some "ERROR: Duplicate FITID in <STMTTRN>:..." errors. I can assure that the transactions refer to the same <ACCTID>. Can this be the cause of the unsuccessfull MSMoney 2005 Accounts Update? Regards, Marco Mendon=E7a. In microsoft.publi...

Windows 7 fails configuring updates
Windows 7 fails configuring updates OS: Windows 7 Ultimate 64 bit Antivirus: Avira AntiVir Personal RaZ123121 wrote: > Windows 7 fails configuring updates > OS: Windows 7 Ultimate 64 bit > Antivirus: Avira AntiVir Personal All updates or a specific one ? When did this issue start to occur ? Click the Start orb > type the following in the Search field windowsupdate.log Under Programs, click on windowsupdate.log Scroll all the way to the bottom of the log for the most recent entries. Copy and paste at least the last 50 or so lines of the log into your repl...

Create timeline for 2500 B.C. to 100 B.C.?
Visio only allows me to create timeline for after 1900 AD. Can I use Visio to create a timeline for 2500 BC to 100 BC? Visio's Divided timeline has exactly what I need except I can not enter BC as the start and end time. And Visio always require end time to be greater than the start time. Any suggestion on how I can do this in Visio? You're not going to be able to use the timeline because the code is linked to the system clock (only goes back to 1900). You'll have to use the vanilla shapes that come with visio. Al "Little Black Sheep" <Little Bl...

Operation failed message
I just installed Outlook 2002. I created a number of email accounts and assign them to the Outlook.pst file. Every time I click on the Send and Receive All Messages, an error message appears reading "Operation failed". I cannot figure out what I did wrong during the installation process. Can you help me? Thanks in advance, Oscar ...

Visual C++ to read Strings from Serial Port
Hi. I'm doing a project using Visual C++ to read data from Serial Port. My program needs to do *something* when it receives specific data. For eg, if the program receives "Alarm 1 Zone 4", it will do something. The data received will be variable in length. My questions: 1) Any recommendations for the serial Comm Class for Visual C++? 2) How can i compare the data i receive from serial to the specific messages i'm looking for, eg data types, size of data types, limitations & etc.? Thanks. Any comments are highly appreciated. Leng As far as the serial part goes, it i...

Microsoft Offide for Mac 2004 Causes Sleep Problem
After installing the latest update for Office for Mac 2004, my G4 will not fall asleep automatically according to the setting in System Preferences. I can put it to sleep manually, but since I don't always know when I am not coming back to the computer for awhile, this is an issue for me. Can anyone help? Is it possible to uninstall this update, or would it involve uninstalling all the Office apps and starting over? I sure hope not. H.G. On 5/28/07 5:34 PM, in article 1180398840.085234.35540@q69g2000hsb.googlegroups.com, "CALF@swbell.net" <CALF@swbell.net> wrote: > A...

Outlook 2003 Constantly Fails
Outlook 2003 constantly fails or hangs .. anyone experienced this problem? Know what the problem is? Thanks. Know what the problem is? Um, lack of any shred of information for troubleshooting perhaps? --� Milly Staples [MVP - Outlook] Post all replies to the group to keep the discussion intact. Due to the (insert latest virus name here) virus, all mail sent to my personal account will be deleted without reading. After searching google.groups.com and finding no answer, Clarissa asked: | Outlook 2003 constantly fails or hangs .. anyone | experienced this problem? Know what the problem...

Trigger GL DIST#10 Registration Failed
I'm running GP9 and all my users are now receiving a "Trigger GL DIST#10 Registration Failed" message when they login. Any ideas? Thanks The issue has been resolved. For some reason an option on a GP 3rd party module (Act Now by Hawk Mountain) which we don't own got activated which triggered the message. The option has been deactivated and the message is no longer appearing. "JDR - Hotmail" <jdrut10@hotmail.com> wrote in message news:035A5870-8900-45E2-B58C-77859A481F6C@microsoft.com... > I'm running GP9 and all my users are n...

C++ : Is it lots harder than c# and VB
Hi everyone, I learned Java whilst at university and have taught myself c# and VB.net. I think I am ok at it. I was thinking, these languages will probably be bigger in the future so I better get ready for them. But then, I also realised that COM is still quite important and so is C++. So I thought I better just try and have a look at C++ and COM. And now I'm scared. So my question is - why does C++ look so much harder than c#? For example : 1. The methods all have really stupid names that are hard to descern a function from. 2. You need to think about pointers and cleaning up ...

MFC DLL Calling C# Assembly
I have been trying to get a simple mfc dll I wrote to add to numbers call a C# assembly. Here is a sample of my C++ code in my cpp file. extern "C" _declspec(dllexport) int Calc(int no1,int no2) { //result = no1 + no2; return MangedAdder(no1, no2); } #pragma managed #using <mscorlib.dll> #using <ControllerLibrary.dll> int MangedAdder(int a, int b) { ControllerLibrary::DLLController *t = new ControllerLibrary::DLLController(); return t->AddNumbers(a, b); } All I really need is an extern function in a mfc dll that calls a me...

Why is ::BeginPaint causing a WM_ERASEBKGND to be sent?
Hi, I have found that the constructor for CPaintDC, which calls ::BeginPaint passing in the HWND on which we want to paint on, generates a call to WM_ERASEBGND before returning. This is not desirable in many cases. What is going on and what can I do to change this behavior? One hypothesis I have, is that ::BeginPaint checks the WNDCLASS of the HWND received and according to its properties, sends the WM_ERASEBKGND message. However, I have yet to find a case where it does not send it... -- Thanks in advance, Juan Dent, M.Sc. >I have found that the constructor for CPaintDC, which cal...

send as causes undeliverabel
I am running outlook 2003 and exchange 2003 on SBS2003 I have followed the proceedure in KB327000 (How To Grant "Send As" and "Send on Behalf" Permissions in Exchange 2000 Server). When I try and use the send as feature I use the from button and select the user from the global address list. I then get a response back that states "You do not have permission to send to this recipient" This happen whether the recipient is local or remote. How do I get "send as" to work. Send on behalf of will not be an acceptable soloution Wesley Wesley wrote:...

C#.net windows application
Since I am new to c#.net 2008 but I have worked a little with visual basic.net 2005, I have the following questions I would like to ask: 1. When I am looking at a .sln file that I will be maintaining a work, I can see there are lots of static void Main() methods in a file called program.cs throughout the solution in separate folderts. Can you tell me the purpose of this kind of code? Does this instantiate an object, is this a class libary member? 2. When running the C#.net 2008 professional version windows application, how do I know which 'main' method is being called? ...

Type Casting in C and C++
Hello NG As an old style programmer I've been casting values with the C-syntax like: double dVal=3.14; float fVal = (float) dVal; but now I've been told that the C++ syntax should do a better job float fVal = static_cast <float>(dVal); for some reason. Is this true? Will the C++ compiler really generate different (better?) code or is it simply more writing I have to do? Thanx Richie >As an old style programmer I've been casting values with the C-syntax like: > >double dVal=3.14; >float fVal = (float) dVal; > >but now I've been told that the C+...

Distribution list causes "An internal support function returned an error"
Hello, I am using Outlook 2007 on XP Pro SP2. Every time I try to send a message using this one distribution list I get the error message "An internal support function returned an error". How can this be fixed? Recreate the DL from scratch. DL's are not reliable and never work for very long. -- Russ Valentine [MVP-Outlook] "BBran" <bbran@nowhere.com> wrote in message news:e5MYdzl5HHA.2208@TK2MSFTNGP06.phx.gbl... > Hello, > > I am using Outlook 2007 on XP Pro SP2. Every time I try to send a message > using this one distribution list I get ...

WindowsUpdate_00000643 fail
I am running Windows Vista. I have tried loading the updates and after the instalation it shows: Some updates were not installed. Failed: 1 update. When I click: Get help with this error it shows me: 4 results for : 'WindowsUpdate_00000643" "WindowsUpdate_dt000" 1. Troubleshoot problems with installing updates 2. WindowsUpdate error 8024402C 3. WindowsUpdate error 80070422, 80244019, or 8DDD0018 4. WindowsUpdate error 80070643 Has anyone else had the same problem and has a solution? What's the KB number of the failed update? Are you running ...

C, C++ and C# Forums
Throne Software has opened up C, C++ and C# Forums at: http://www.thronesoftware.com/forum/ Join us! ...

C# extension functions using MSXML?
I'm having performance/memory problems using .NET's XslTransform class so I thought I'd give the MSXML object's a whirl. The question I haven't been able to find in these groups is can I use C# extension functions with the MSXML objects? More specifically to use a C# class which has all my extension functions. I've seen examples where the stylesheet uses the <msxsl:script> element and embeds C# code, but that's not a viable solution for my situation since I'll be maintaining lots of different stylesheets which require the same extension functions. (if ...

WLM causes system reboot.
For the last few days, when I open Window Live Mail, I get an error that the last message had a problem and I need to click a link to proceed. Before I can do that XP Home reboots. I have tried reparing WLM, uninstalling and reinstalling, but to no avail. I have even tried to restore XP to a previous restore point, but it won't work because of a unintended system shut down. Any suggestions? Hi, Digdoc. That "last message" might, indeed, be corrupted - or malicious - in some way. But you should be able to delete it by using your browser to visit http://mail...

Outlook link fails when sending email from Publisher
This may be an Outlook problem. -- When I send from Publisher to email as a message I get a fatal failure of the Contact Manager (I assume the one added on in Outlook) after the send begins. The addressing form for the mail comes up and the addresses insert fine. However, I when I click send I get a variety of messages that ultimately end with a failure to engage Outlook. If I now restart both Publisher and Outlook, everything seems to work right. If I boot however, I get the same (or similar) failure. I suspect I need to reinstall Outlook (by the way, I did run Detect and Repair)....

for some reason when i deploy my C# application on windows 2003 occasionaly rdr[0].ToString() hangs where rdr is a System.Data.SqlClient.SqlDataReader. Is there a fix for this? is my visual studio.net
for some reason when i deploy my C# application on windows 2003 occasionaly rdr[0].ToString() hangs where rdr is a System.Data.SqlClient.SqlDataReader. Is there a fix for this? is my visual studio.net out dated? Hi, 1. Does this seem to you to be the right Newsgroup to ask this question ? I would have suggested "microsoft.public.dotnet.framework.adonet". 2. Is there supposed to be a difference between the Message Subject and the Message body ? Isn't the Message Subject supposed to be abbreviated ? 3. As for your question : I strongly doubt if your VS.NET can be called "o...