How to use COM Interop in C#

Nataraj1978's Avatar, Join Date: Feb 2006
Newbie Member
I have a requirement to use a dll written in Visual C++ 6.0 in my C# application. In order to establish the link between my application and the dll, I have written a ATL COM Component in Visual C++.NET [visual studio .NET version 8]. This COM component is referenced in my C# application. The COM component statically links with the 6.0 dll.

I am facing problems in passing data from C# to the dll through the COM component.

1. The dll exposes a function as:
__declspec(dllexport) int __stdcall ProblemFunction(int param1, BYTE param2, BYTE param3, BYTE *param4, DWORD *param5);

2. In the COM wrapper component, I have declared an interface method as:
[id(25), helpstring("method ProblemFunc")] HRESULT ProblemFunc([in] SHORT param1, [in] BYTE param2, [in] BYTE param3, [in, out] BYTE* param4, [in, out] LONG* param5, [out, retval] BYTE* param6);

where, param6 is used to return the value returned by dll function to the C# client application.

The implementation of this interface function is given below:
Wrapper::ProblemFunc(SHORT param1, BYTE param2, BYTE param3, BYTE* param4, LONG* param5, BYTE* param6)
*param6 = ProblemFunction(param1, param2, param3, param4, (DWORD*)param5);
return S_OK;

3. In the C# client application, I am calling the COM function as:
byte returnValue = DllWrapperObject.ProblemFunc(value1, (byte)value2, (byte)value3, ref value4, ref value5);

Here, I am facing problems passing value4 and value5 because:
a. For value4 I need to pass a structure.
b. For value5 I need to pass the size of the structure being passed in value4.

The structure to be passed is as required by the dll. The C++ structure is:
typedef struct
DWORD var1;
DWORD var2;

DWORD var3;
char var4[16];
DWORD var5;
} var6[3];

I wrote the structure's equivalent in C# as a class as I had to create an array. The C# implementation of the above given structure is:
internal class InnerStruct
long var3;
char[] var4 = new char[16];
long var5;

internal static int GetSizeOfClass()
return (sizeof(long) + sizeof(char) * 16 + sizeof(long));

internal class TestStruct
long var1;
long var2;
InnerStruct[] var6 = new InnerStruct[3];

internal static int GetSizeOfClass()
return (sizeof(long) * 2 + InnerStruct.GetSizeOfClass() * 3);

1. Is there any better way to define the structure equivalent in C#?
2. How can I get the size of the structure/class for passing it to the dll?
3. How to pass the handle of the structure/class object from C# to the dll so that it can fill it up and return it to the client app for future usage?
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
I am not a expert in C# but I guess this can be done using the PInvoke I guess

Here are some links that can be useful

Sample for PInvoke