Accessing C# Methods and Constructor from C++ program

109 views Asked by At

Created a C# DLL to I/F with a C++ test console app program CSartTest.cpp The C++ recognizes the class defined in the C# DLL (MtXxxxx -- (name obviously changed)) Don't know how to instantiate the object or reference its public methods.

Here is what I have done thus far:

  1. Modified the project to: AssemblyInfo.cs: --
    [assembly: ComVisible(true)] Signing: Project is signed Build:
    Project is Regressed for COM interop
  2. Added an Interface IMtXxxxx.cs (obviously XC=XXXX is not the true name) -- Added: [ComVisible(true)] [Guid ("1fd98919-18b7-4b41-9a08-c7e74f09d6bd")] [InterfaceType(ComInterfaceType.InterfaceIsDual)]
  3. For the main Class added: [ComVisible(true)] [Guid("e82e2cf6-67dc-4574-b579-ff1452943271")] [ClassInterface(ClassInterfaceType.None)] [ProgId("LTA_MT.MtXxxxx. ")]
  4. Solution compiles and creates a tbl file -- LTA.MT.tlb
  5. In the C++ project added the generated .tbl file
  6. In the main program in the C++ console app -
    added: at the top of the file: #include <tchar.h> #import "<Path to tbl file>\LTA.MT.tlb" raw_interfaces_only (path has "\" in it using namespace LTA_MT; in int main() HRESULT hr = CoInitialize(NULL); MtXxxxx *busessRules = NULL; 7. In Tools/Options/Debugging/Symbols -- Checked Microsoft Symbol Servers

Solution compiles and executes However: A. Don't know how to instantiate the C# object B. Can't seem to get IntelliSense working for object busessRules

What am I missing -- Please help -- Thanks

Googled interfacing between C++ and C# a lot -- don't fully understand all the answers I found --

Tried to include #using <mscorlib.dll> but got a compiling error

Thought about adding and including a header file #include <CShartTest.h> but that did not seem to work

As I said, not very proficient in C++ at this time -- Have not used in in decades and am very rusty.

Would like very simple step by step instructions -- Thanks

1

There are 1 answers

5
Blindy On

There's a lot of clutter in your question, but you seem to be asking how to instantiate a COM object in C++, and the answer is simple: CoCreateInstance. Your IID_ and CLSID_ definitions should be imported from your .tlb file.

Tried to include #using <mscorlib.dll> but got a compiling error

That's a different approach from yours, where you don't use COM objects to proxy messages between your native application and .Net, but instead you make your C++ application managed so it can directly reference your managed library. Much, much easier (and faster!).