Send struct between a C# DLL and a C# application


A

Alain Dekker

Hi,

I've got a structure in a C# DLL defined as follows:

// DLL struct
public struct DataLinkDiag
{
public int data1; // Count of data1 calls
public int data2; // Count of data2 calls
}

And I've defined a function in the DLL to return the structure

// DLL code continued
public static DataLinkDiag diag;

// ... maybe set some members of the structure like diag.data1++; and so on

public static DataLinkDiag GetDatalinkDiag()
{
return diag;
}

Now in the C# application I have defined the same structure (exactly as
above) and then I try and populate a local variable from the DLL:
// C# application code
CCommonDefinitions.DataLinkDiag datalinkDiag = new
CCommonDefinitions.DataLinkDiag();

// ...

datalinkDiag =MyDll.GetDatalinkDiag();

The DLL compiles fine. But when I compile the C# application, it fails with
this compiler message:
Cannot implicitly convert type MyDll.DataLinkDiag' to
'CCommonDefinitions.DataLinkDiag'

What am I doing wrong? This was easy to do in C++ if I remember correctly.

Thanks,
Alain
 
Ad

Advertisements

J

Jeff Johnson

Now in the C# application I have defined the same structure

And there's your problem. You should just reference the DLL from the C#
application and then use the DLL's version of the structure. If this is not
possible then you don't really have much choice other than copying each
member of one structure to the other manually. C# doesn't care one bit that
the structs have the exact same layout; it thinks they're different and will
not allow a simple struct1 = struct2 assignment.
 
A

Alain Dekker

OK, understood. In the C++ world I was just casting the one onto the other
because they were bit-for-bit identical. C# is being a bit more literal
about the types, which on balance is better, I guess. I've referenced the
type from the DLL directly and it all works.

Thanks!
Alain
 
Ad

Advertisements

A

Arne Vajhøj

OK, understood. In the C++ world I was just casting the one onto the other
because they were bit-for-bit identical. C# is being a bit more literal
about the types, which on balance is better, I guess. I've referenced the
type from the DLL directly and it all works.

Even in C++ it is not a nice solution, you will need some nasty
casts to make it work.

The nice C++ solution would be a header file included in both.

Setting ref to an assembly in .NET is somewhat similar to
including the header file in C++.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top