Click here to Skip to main content
14,448,968 members
Rate this:
Please Sign up or sign in to vote.
See more:
Returning a structure from a call to a DLL to C#

Here is my code in 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:
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 5:06am
v2
Comments
Piccadilly Yum Yum 7-Mar-11 10:12am
   
You had to use Marshal class
Rate this:
Please Sign up or sign in to vote.

Solution 1

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

public struct abc
{
    public int a;
    [System.Runtime.InteropServices.MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
    public int[] b;
}
   
Comments
   
Correct, a 5.
--SA
Rate this:
Please Sign up or sign in to vote.

Solution 2

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...
   
Comments
   
Correct, a 5.
--SA

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100