Click to See Complete Forum and Search --> : C# wrapper, C++ struct containing CList


DHarman
December 3rd, 2009, 03:10 PM
I have a C++ DLL using MFC and I need to wrap all the exported functions so they can be used by a C# .NET front end. For functions taking CStrings, ints, etc this isn't a problem. However, I have some functions which take a struct as a parameter. The problem is, the struct contains a CList of another struct...for example:


struct SOne
{
CString str1;
long l1;
CString s2;
int i1;
};

struct STwo
{
CList <struct SOne,struct SOne&> myList;
CString str1;
int i2;
};

//The exported function looks like this (export syntax left out for simplicity)
long DoSomthing(struct STwo* me);


So how do I marshal the data for STwo within my wrapper so that DoSomething can be called from a C# front end?

Sorry if I'm using incorrect terminology. I'm a C++ programmer just now venturing into C# so all the C# syntax is new to me.

Thanks in advance for your help.

darwen
December 3rd, 2009, 05:46 PM
Erm - quick answer is you can't. C# has no way of reading C++ classes like CList etc.

But you can write proxy classes in C++/CLI which contain your structs and that C# can read.

In this case I think this would be your easiest option.

Darwen.

DHarman
December 4th, 2009, 07:38 AM
Thanks for the reply. I knew that C# didn't understand CList (or CString for that matter). I'm not exactly sure what you mean by a proxy class...I think that's what I'm calling my "wrapper". I'm writing a C# class that my C# .NET GUI will make calls to. Then, that C# class needs to covert the C# data into data the C++ DLL will understand and call the exported C++ DLL functions. I just need to know how to get the data in the right format. I figured there wasn't an easy "MarshalAs" equivalent. In the case where you can't just marshal data, how do you convert it....say from a list <T> to my C++ CList?

For a struct with just normal data, you can just use the [StructLayout] tag and create the struct as a class (at least that's what I've seen elsewhere on the web). I just can't find any data on using a struct that contains lists...I've seen examples using fixed arrays, but I'll have no way of knowing how many nodes are in my list at design time so those examples won't work for me. If you could provide a simple example using my example layout in my original post I would greatly appreciate it. Remember I'm brand new to C# so there's no such thing as too many details :-)

Thanks again for the reply.

rohshall
December 5th, 2009, 01:12 AM
I think you have two options:

1. You can change the complex classes/structures into something simpler that can be exported

2. If you do not want to change the complex structures that can't be marshaled, then you need to put the code that deals with these structs in the DLL itself. This DLL will need to export only simple structures that can be marshaled.