C # Call the native C ++ COM Object (implement the C # interface in C ++ ),
For cross-platform.. net core uses COM and cannot use the COM registration mechanism in Windows. However, you can directly pass the IUnknown pointer to C #, convert it to a pointer, and then convert it to an interface of C ).
I did some research in this area, but I didn't use this technology in the end, because the distribution of IDispatch: Invoke is too troublesome, and I cannot use the IDL capabilities of the ATL and VS development environments. So we didn't continue to study event subscription (C # Is event, C ++ COM is IConnectionPoint ).
What needs to be done in C ++:
Simply put, implement IDispatch. To implement IManagedObject or IProvideClassInfo, the latter is a big project.
If we want to implement the interface defined in C #, it is best to give (not to give it, the compiler will give each interface a default GUID) interface a GUID ,. net to your object QueryInterface to process this IID, The IDispatch pointer and S_ OK can be returned.
If it is cross-platform, replace _ uuidof with the actual UUID.
Struct foo: public IDispatch {// inherits virtual ULONG AddRef (void) override {return 0;} virtual ULONG Release (void) override {return 0 ;} virtual HRESULT QueryInterface (REFIID riid, void ** ppvObject) override {if (riid = _ uuidof (IUnknown) {* ppvObject = (IUnknown *) this; return S_ OK ;} IID uid; IIDFromString (L "{C # declaration interface GUID/IID}", & uid); if (riid = uid) {* ppvObject = (IDispatch *) this; // (IUnknown *) this; return S_ OK;} if (riid = _ uuidof (IDispatch) {* ppvObject = (IDispatch *) this; return S_ OK ;} return E_NOTIMPL;} virtual HRESULT GetTypeInfoCount (UINT * pctinfo) override {return S_ OK;} virtual HRESULT GetTypeInfo (UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo) override {return S_ OK ;} virtual HRESULT generator (REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId) override {* rgDispId = 1; return S_ OK;} virtual HRESULT Invoke (DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, interval info * p0000info, UINT * puArgErr) override {cout <"be called" <endl; return S_ OK ;}};
Export a DLL function to give the pointer to. net runtime.
Extern "C" _ declspec (dllexport) foo * WINAPI GetTestObject () {return new foo; // simple and crude leak :)}
C # code:
[DllImport (@ "foo. dll ")] static extern IntPtr GetTestObject (); [InterfaceType (ComInterfaceType. interfaceIsIDispatch)] [Guid ("your uiid")] interface Test {int func ();} var v = GetTestObject (); obj = (Test) Marshal. getObjectForIUnknown (v); var value = obj. func (); // output be called
I love COM
The idea of COM is very important. COM has recently been active on not only Windows platforms, but also Linux, Android, iOS and other platforms. Architects and programmers should make proper use of the data.