Use C # To compile sample code for a COM component outside the process

Source: Internet
Author: User

CodeIn 《UseC #Compile an external processComComponentsTIPS: If you want to read the sample code and explanations at the same time, you can open the sample code andArticleAnd then useWindowsThe vertical tiled window function allows you to read two articles at the same time.

 

Testcomvisibleclass . CS Which defines what we want to publish Com CustomerProgramOf . NetObject, because our . Net The number of external components that need to be called Com Library API Therefore Comhelperclass Define these API In . Net The declaration method in, correct declaration P/invoke The function prototype is very difficult and requires the programmer Win32 , Com It can be done only when you are familiar with the managed code, so I wrote another article titled 《 Use signature ToolAutomatic GenerationP/invokeCallWindows APIOfC #Function Declaration Simplified P/invoke Function declaration steps.

 

Comhelperclass Class Coregisterclassobject The function prototype is interesting. Note that Rclsid The [Financialas (unmanagedtype. lpstruct)] Property. This property tells . Net, In . Net Transfer at one end Rclsid Do not use the default column set ( Marshal ) Rules, in P/invoke Inside, Net By default, the struct object is completely copied to the unmanaged memory. Unmanagedtype. lpstruct Tell Net Set Guid The object pointer is passed to an unmanaged function, saving the need to add Ref Keyword troubles, Unmanagedtype. lpstruct There will be another article to explain it, which is somewhat special. . NetBy default, class instance object columns are integrated. Variant Copy to the unmanaged memory, so the second parameter is used [Financialas (unmanagedtype. iunknown)] Notification . Net This object instance column needs to be integrated Iunknow * Pointer.

 

our . net external components may be C ++ the client is called. For the C ++ program, it is more convenient to bind before use (that is, call the interface member function through the interface pointer, otherwise, call the interface member function through the idispatch API) C ++ the code is more complex. Therefore, testcomvisibleclass are extracted as an interface, itestcomvisible interfaces and testcomvisibleclass A guid , in the com world, the former is well-known IID, the latter is CLSID .

 

At the same time, for convenienceVBProgram usage. NetExternal components, I also specifically giveItestcomvisibleThe interface attributes and functions specifyDispidBecause inOleIn the specification,DispidIs0,-1Several Functions with special values have special meanings, which will be discussed in the following articles.

 

Because we cannot use Mscoree. dll In Com To activate our . Net Object, Mscoree. dllThe activation policy provided by default will also be described in the following article. we have to provide the class factory explicitly and put our class factory in Com Register it in the Runtime Library. Factory ( Classfactory ), You also need to define C # Form prototype, a more clever way is to use Tlbimp Generate DLL Or you just need to see System. runtime. interopservices. comtypes Is there any defined type in the namespace? Iclassfactory The most important function is Createinstance The implementation is to see what interfaces The client needs. Iunknown Or we released Itestcomvisible ( 102 To 107 Line). Otherwise 109 The row location throws an exception (the habit of throwing an exception when an error occurs is Com In the world, it is not a friendly method. For the sake of simplicity, My Code adopts the exception throwing method. A better way is to return the error code. Com The client determines how to handle this error .)

 

When the program starts, we register the self-implemented class factory inComIn the Runtime Library (Program. CSOf48To53Rows), remember to keepCoregisterclassobjectReturned registration to usID(53Rows ).Program. CSInside35To44Optional. They are designed to perform security checks to ensure that only authorized users can call yourC # DCOMIf you are not interested in security, you can delete them. When the program exits (Program. CSOf26To29(Rows) remove some tails and release some resources.

 

Why do we need a registry file? This is because in the previous binding call method, we need to pass the pointer between processes, for example, in the client C ++The 21 Row, actually Cocreateinstanceex We need to start our . Net Process (that is, outside the process) Com Server ). Program. CS The 53 The row has been registered Iclassfactory Interface to create . Net Object instance, and then Itestcomvisible Interface pointer from . Net Process return C ++ Client process. Someone may say that the pointer address can be directly directed C ++ What about the client process? This is not acceptable, because Windows The operating system separates the process from other processes. Simply put, the virtual memory address in a process may point to a garbage in another process, for details about the principles, see the virtual memory description in the operating system book.

 

To pass between processes Itestcomvisible Interface pointer, Com Library needs to know how to set Columns Itestcomvisible Pointer. In general, the programmer needs to provide another DLL , This DLLContains a column set Itestcomvisible Pointer code. The reason why code is provided for column set pointers is that different interfaces contain different functions, such C ++ The 25 Row and number 26 Row, Com Library requires remote function call of the column set ( RPC ), That is, a method is required Testmethod And Release Are separated. Generally DLL , You can use Msidl.exe Analysis IDL File to generate a column set functionSource codeCompile and generate. However, this method is troublesome, So Microsoft provides Oleaut32.dll , There is a general interface column set function (but this function cannot list all interfaces, you can follow some rules for the column set interface, this will be discussed later), you can through analysis TLB File, because TLB File equivalent . Net assembly Metadata, Oleaut32.dll You can understand your Com What interfaces are in the component, what are the declarations of each interface, and what are the parameter types of the function. However Oleaut32.dll You need to query the Registry to know that the interface already exists. TLB File Location:

1.Therefore,3Line16The row stores the path of the Type Library in the registry. Note thatComIn the world,TLBFiles are also usedGuidYou can useOleview.exeOpenRegasm.exeOrTlbexp.exeGeneratedTLBFile, find[Custom (9903f14c-12ce-4c99-9986-2ee3d7d588a8)…]Find the paragraphTLBFileGuid.

2. In the registry code 18 Line 28 Row. The column set is saved in the registry. Itestcomvisible Interface information, such Proxystubclsid Indicates Oleaut32.dll Provides a common interface column set function, and saves TLB File Information 26 To 28 Rows ). If the registry does not contain information about the column set interface, Cocreateinstanceex The function returns E_nointerface (This interface is not supported) Error - A confusing error code.

3.Finally,30Line41I declare to the World (Sorry, it is not the statement that the Chinese people have stood up since then): Our. NetThe object does not need to passMscoreeLaiyouComTerminal activation, you can complete the activation operation, so we deletedRegasm.exeInsertedInprocserver32Key value, but addedLocalserver32Key value.

 

Appendix, 3 line to line 28 registertypelib function to complete, registertypelib required ptlib you can use loadtypelib function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.