简体   繁体   English

pinvoke从c中的struct获取数据

[英]pinvoke get data from struct in c

I am using pinvoke in a project I am building. 我在正在构建的项目中使用pinvoke I need to get data from a function in C, the function gets pointer to a struct. 我需要从C中的函数获取数据,该函数获取指向结构的指针。 In my c# I did a class with the appropriate attribute(layountkind.sequntial). 在我的C#中,我做了一个具有适当属性的类(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. 我在函数中填充了该结构,但是当它退出该函数时,该类的实例没有在c中填充的值,因此我在退出c函数之前检查了指针的内容,并且它具有正确的值。 Below is the prototype of the function: 下面是该函数的原型:

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

My struct in C#: 我在C#中的结构:

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

function and struct in C: 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. p / invoke声明不正确。 The default marshalling is In only. 默认编组是In唯一的。 But you need Out marshalling. 但是您需要进行Out编组。 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. 我个人认为使用C#结构会更惯用。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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