Need help on passing classes from from C++ to C# and using them in C# via DLL.

Hello. I need help on how to correctly pass classes from C++ to C#.

I've been following this article:
http://limbioliong.wordpress.com/2011/06/12/returning-a-c-class-from-an-api-in-c/

But this method for some reason crashed my aplication.

To start things of, here is my example on what I would like to achive:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
extern "C" __declspec(dllexport) CTestClass* TestAPI01(int i)
{
        // Get the size of the class.
        size_t  stSize = sizeof(CTestClass);
        // Allocate in the global heap a block of memory
        // large enough for an instance of the class.
        CTestClass* pTestObject = (CTestClass*)(GlobalAlloc(GMEM_FIXED, stSize));
        // Create a temporary instance of the class and assign its values
        // to the instance in the global heap.
        *pTestObject = CTestClass(i);
        // Return the global heap class instance.
        return pTestObject;
}


C# (a little different from the article)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
	internal struct CTestClass
	{
		private int  m_int;
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
		private string m_szString;
		[MarshalAs(UnmanagedType.LPStr)]
		private string m_pStr;
	};
[DllImport(pluginName)] public static extern IntPtr TestAPI01(int i);
	public static CTestClass CreateMyClassStruct()
	{		
		CTestClass test = new CTestClass();
		Marshal.PtrToStructure(TestAPI01(i,str),test);
		return test;
	}


So what changes should I make to have it functional?
Ideally this is how id like to use the C++ class in C#:

[DllImport(pluginName)]
public static extern IntPtr CreateMyClass();
[DllImport(pluginName)]
public static extern float GetFloatFromMyClass();
[DllImport(pluginName)]
public static extern void ModifyMyClass(IntPtr myClass, int num);


Any ideas on how to achieve this? Thanks in advice!
So far, this article seems to cut the deal:
http://www.codeproject.com/Articles/18032/How-to-Marshal-a-C-Class

Topic archived. No new replies allowed.