简体   繁体   中英

pinvoke get data from struct in c

I am using pinvoke in a project I am building. I need to get data from a function in C, the function gets pointer to a struct. In my c# I did a class with the appropriate attribute(layountkind.sequntial). Before the function I do:

mystruct str=new mystruct();
str.Data=new byte[14];
func(str);

I fill the struct in the function but when it exit the function the instance of the class doesn't have the values i filled in c,i check the content of the pointer before i exit the c function and it has the right values. Below is the prototype of the function:

[DllImport("mydll.dll", CallingConvention=CallingConvention.Cdecl)]
void func([MarshalAs(UnmanagedType.LPStruct)] mystruct str);

My struct in C#:

[StructLayout(LayoutKind.Sequential)]
public class mystruct
{
    public ushort familiy;
    [MatshalAs(UnmanagedType.ByValArray,SizeConst=14)]
    public byte [] data;
}

function and struct in C:

struct sockaddr{
 unsigned short familiy;
 char data [14];
};
    void func(struct sockaddr *info)
{
int i;
char buffer[100]
recvfrom(sockfd,buffer,0,info,&i);//assume i have a global varible sockfd and it is an open socket
}

How can i fix my problem?

The p/invoke declaration is incorrect. The default marshalling is In only. But you need Out marshalling. Otherwise the marshaller won't attempt to marshal the data set by the unmanaged function back to the managed class.

So you can fix the problem by declaring the function like this:

[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void func([Out] mystruct str);

Personally I think that it would be more idiomatic to use a C# struct. I'd declare it like this:

[StructLayout(LayoutKind.Sequential)]
public struct mystruct
{
    public ushort family;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=14)]
    public byte[] data;
}

And then the function becomes:

[DllImport(dllname, CallingConvention = CallingConvention.Cdecl)]
static extern void func(out mystruct str);

And the call is simply:

mystruct str;
func(out str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM