Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
4.67/5 (3 votes)
See more:
Returning a structure from a call to a DLL to C#

Here is my code in C++
C++
struct abc
{
    int a;
    int b[5]
};

struct abc mystruct()
{
    struct abc a1;
    a1.a=12;
    for(int i=0;i<5;i++)
        a1.b[i]=i*i;
    return a2;
}



I want to call this function in C# Win32 application after having created the DLL in C++. My C# structure is like this:
C#
public struct abc
{
    public int a;
    public int []b;
};

[DllImport("C:\\mydll.dll")]
public static extern abc mystruct();

private void button5_Click(object sender, EventArgs e)
{
    abc a2=new bcd () ;
    a2.b = new int[5];
    a2 = mystruct(10);
}




Whenever I compile it it givse me this error:
"Method's type signature is not PInvoke compatible."

Can anyone please provide me a solution to this problem. If I remove the array from the struct it compiles successfully.

Thanks in advance!
Posted
Updated 7-Mar-11 4:06am
v2
Comments
Piccadilly Yum Yum 7-Mar-11 10:12am    
You had to use Marshal class

Hi,
you have to provide the size of the array.
Try the following:

C#
public struct abc
{
    public int a;
    [System.Runtime.InteropServices.MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
    public int[] b;
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 7-Mar-11 12:03pm    
Correct, a 5.
--SA
Your marshalling is wrong. Marshal the b[] field of your struct with [System.Runtime.InteropServices.MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] or use unsafe code
public fixed int b[5].
Btw your example code is wrong (bcd, a2.b = new int[5], mystruct(10)). Please test before posting...
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 7-Mar-11 12:03pm    
Correct, a 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900