
Signature
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.
Hi John,
I aggree with our MVP, and here is a simple example:
If you still have problem on this issue, please let me know.
Thanks for using MSDN Newsgroup!
<code unmanaged part>
typedef struct _mytype
{
int *data;
}mytype;
extern "C" __declspec(dllexport)
mytype* init(int size)
{
mytype *p_mytype = new mytype();
p_mytype->data = new int[size];
for(int i = 0; i < size;i++)
{
p_mytype->data[i] = i;
}
return p_mytype;
}
</code unmanaged part>
<code>
using System;
using System.Runtime.InteropServices;
namespace Interop_CS
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
int size = 10;
IntPtr p = init(size);
MyType t = Marshal.PtrToStructure(p,typeof(MyType)) as MyType;
int[] s = new int[size];
Marshal.Copy(t.data,s,0,size);
//read from the data
for(int i = 0; i < size; i++)
{
Console.WriteLine(s[i]);
}
//change the s
//write it back to t.data
Marshal.Copy(s,0,t.data,size);
//you should provide an corresponding function do free the memory.
//free_mytype();
}
/*
typedef struct _mytype
{
int *data;
}mytype;
*/
[StructLayout(LayoutKind.Sequential)]
public class MyType
{
//because you allocated memory in your unmanaged code, we can't marshal
it to array.
//or the address will lost, and the memory will not be freed.
public IntPtr data;
}
[DllImport("Interop_DLL_Stub.dll")]
public extern static IntPtr init(int size);
}
}
</code>
Best regards,
Ying-Shen Yu [MSFT]
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties and confers no rights.
You should not reply this mail directly, "Online" should be removed before
sending, Thanks!
--------------------
| From: Mattias Sj?gren <mattias.dont.want.spam@mvps.org>
| Subject: Re: Can C function return pointer-to-structure to C#?
[quoted text clipped - 26 lines]
|
| Mattias