/*下面是C代码,最终编译成DLL库,库名为student.dll*/
struct student
{
char name[123];
int age;
};struct student* GetStudent()
{
struct student *p_my_student = (struct student*)malloc(sizeof(struct student)*sizeof(char));
strcpy( p_my_student.name,"David");
p_my_student.age = 28;
return (p_my_student);}/*下面为C#代码,使用非安全方式调用dll库*/
namespace studentIntf
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[StructLayout(LayoutKind.Sequential)]
public struct student
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public byte[] name;
int age;
};
[DllImport(UTSQLITE_DLL)]
public unsafe static extern student* GetStudent();
private void button1_Click(object sender, EventArgs e)
{
unsafe
{
GetStudent();
}
}
}
}上述代码编译通不过,错误提示是:无法获取托管类型(“studentIntf.student”)的地址和大小,或无法声明指向它的指针
请问:即然使用了非安全(unsafe)方式,还不能返回结构体的指针吗?接下来我用下面的方式(IntPtr)来调用库
namespace studentIntf
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} [StructLayout(LayoutKind.Sequential)]
public struct student
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public byte[] name;
int age;
};
[DllImport(UTSQLITE_DLL)]
public unsafe static extern IntPtr GetStudent(); /*区别*/
private void button1_Click(object sender, EventArgs e)
{
unsafe
{
IntPtr = GetStudent(); /*区别*/
} }
}
} 上述代码编译通过,但我不知道如何将IntPtr转换成struct student*,请问如何转换?或者有什么更好的办法来处理DLL返回结构体指针的问题
struct student
{
char name[123];
int age;
};struct student* GetStudent()
{
struct student *p_my_student = (struct student*)malloc(sizeof(struct student)*sizeof(char));
strcpy( p_my_student.name,"David");
p_my_student.age = 28;
return (p_my_student);}/*下面为C#代码,使用非安全方式调用dll库*/
namespace studentIntf
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[StructLayout(LayoutKind.Sequential)]
public struct student
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public byte[] name;
int age;
};
[DllImport(UTSQLITE_DLL)]
public unsafe static extern student* GetStudent();
private void button1_Click(object sender, EventArgs e)
{
unsafe
{
GetStudent();
}
}
}
}上述代码编译通不过,错误提示是:无法获取托管类型(“studentIntf.student”)的地址和大小,或无法声明指向它的指针
请问:即然使用了非安全(unsafe)方式,还不能返回结构体的指针吗?接下来我用下面的方式(IntPtr)来调用库
namespace studentIntf
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} [StructLayout(LayoutKind.Sequential)]
public struct student
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public byte[] name;
int age;
};
[DllImport(UTSQLITE_DLL)]
public unsafe static extern IntPtr GetStudent(); /*区别*/
private void button1_Click(object sender, EventArgs e)
{
unsafe
{
IntPtr = GetStudent(); /*区别*/
} }
}
} 上述代码编译通过,但我不知道如何将IntPtr转换成struct student*,请问如何转换?或者有什么更好的办法来处理DLL返回结构体指针的问题
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货