Delphi 線程裏面調 COM 對象時提示 CoInitialize 尚未被呼叫 出錯

在一次用寫windows Server 應用程序的時候,寫了一個調用.net 的webservice的類,測試調用沒有異常。在用windows server應用程序 加個線程類調用 這個類的時候,出現 “CoInitialize 尚未被呼叫” 的錯誤,錯誤斷點停在OPToSOAPDomConv.pas上面的一行代碼“  XMLDoc.Encoding := SUTF8; ”, 可能 XMLDoc 又調用的時COM對象的緣故吧,結果提示  CoInitialize 尚未被呼叫 。

然後拼命google,找到了一個解決的方法(來源"http://topic.csdn.net/t/20030916/14/2265433.html"),來自leapmars的回覆:

procedure   TYourThread.Execute
begin
    CoInitialize(nil);       //   初始化   COM   库
    try
            ......
    finally
        CoUninitialize();
    end;
end;

結果條用的時候沒有錯誤提示了。 記錄下問題和解決,方便以後遺忘或者遇到同樣問題的童鞋查閱

附:Delphi6 調用webservice ,我打了 update2的補丁,在自動生成的單元

// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL     : http://dgqeap/empws/empws03.asmx?wsdl
// Encoding : utf-8
// Version  : 1.0
// (2011/11/2 と 03:13:12 - $Revision:   1.9.1.0.1.0.1.9  $)
// ************************************************************************ //

...

的initialization段修改代碼:

  InvRegistry.RegisterInterface(TypeInfo(EMPWS03Soap), 'http://tempuri.org/', 'utf-8');
  InvRegistry.RegisterDefaultSOAPAction(TypeInfo(EMPWS03Soap), 'http://tempuri.org/%operationName%');

  InvRegistry.RegisterInvokeOptions(TypeInfo(EMPWS03Soap), ioDocument);

  RemClassRegistry.RegisterXSInfo(TypeInfo(GetLeaveEmployeeXMLResult), 'http://tempuri.org/', 'GetLeaveEmployeeXMLResult');
  RemClassRegistry.RegisterXSClass(GetLeaveEmployeeDataTableResult, 'http://tempuri.org/', 'GetLeaveEmployeeDataTableResult');
才調用成功的

其他google都可以容易找到,就不mark了

原文地址:https://www.cnblogs.com/KevinHo/p/2317443.html