Trouble calling COM object from CSharp

linesh

Active member
Joined
Oct 14, 2004
Messages
32
Location
Washington D.C.
I have a COM object written in C++ whose class has functions that i am trying to invoke. I am able to instantiate the object and call some functions on it. However, I am stuck at calling one function which keeps giving me a COMException. Looks like it does not like the signature created in the Interop. I tried creating an IL manually from the type library dll, editing it by adding "preservesig" and readding it, but does not help.

I have included the actual source, the IL equivalent and the CSharp code for it.

In the original source code:

HRESULT Read([in] LPUNKNOWN pPos, [in] long pBuffer, [in] long lBufferLen, [out] long * pData, [in] LPUNKNOWN pInfo)

This is how it looks in IL.

.method public hidebysig newslot virtual
instance void Read([in] object marshal( iunknown ) pdb,
[in] int32 pBuffer,
[in] int32 lBufferLen,
[out] int32& pData,
[in] object marshal( iunknown ) pdbImg) runtime managed internalcall


I think I know the iunknown objects, but i am unsure of the int32& parameter and how to call it from csharp. I tried InPtr (maybe i am using it incorrectly).

Here is the CSharp code (just renamed the library names):

using MyCOMLib;

Int32 buffer = 0;
Int32 frameData;
int bufferLen = 256;

MyComObj MyCOMObjInstance = new MyComObj();
MyCOMLib.MyCOMPosInfo oPosInfo = new MyCOMLib.MyCOMPosInfo();
MyCOMLib.MyCOMObjInfo oInfo = new MyCOMLib.MyCOMObjInfo();

MyCOMObjInstance.Read(oPosInfo, buffer, bufferLen, out frameData, oInfo)

It keeps giving me a COMException with a certain HRESULT. Is there something with the way I am calling it in CSharp or does it need a fix in the IL? Any help or pointers would be greatly appreciated.

Thanks in advance,
Linesh
 
Thanks for your response.

I tried to use VS to generate the wrapper first by adding a reference to the COM dll into the csharp project. But when invoking the function it gives a COMException in the VS generated Interop. So i tried to use ildasm to create the MSIL manually then edit the MSIL after creating it by adding "preservesig" and then generate the Interop using ilasm.

So to answer your question i tried both.

I think csharp does not like the Int32& parameter in the function. In the actual code, this is a long * variable as you can see. But again i might be mistaken in how i am calling the wrapper that was generated.
 
Have you checked to see what the returned HRESULT means? It might indicate the source of the problem if there is an associated error.
 
Yes i did. Currently i am trying to use "Unsafe" keyword and trying to use that to sort of replicate the c++ code. Its not giving the COMException always now, but i am still not getting the desired result.
 
Back
Top