嵌套结构解组 [英] Nested struct unmarshalling

查看:185
本文介绍了嵌套结构解组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个非托管结构

typedef struct multipolynomial
{
    int N;
    int max_power;
    double* X;
    double** Y;
} multipolynomial;

typedef struct output
{
    double d;
    multipolynomial mp;
} output;

和相应的管理类似物

[StructLayoutAttribute(LayoutKind.Sequential)]
public unsafe class Multipolynomial
{
    public int n;
    public int max_power;
    public double* X;
    public double** Y;
}

[StructLayoutAttribute(LayoutKind.Sequential)]
public unsafe struct Output
{
    public double d;
    public Multipolynomial mp;
}

和有本地函数

__declspec(dllexport) output __cdecl foo()
{
    output out;
    out.t = 1;
    return out;
}

与托管签名

[DllImport("kernel.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern Output foo();

在这里崩溃

Output output = MathKernel.foo();

与解释方法的类型签名不兼容的PInvoke。

with explanation "Method's type signature is not PInvoke compatible."

请指出什么问题呢?

PS:请注意,管理模拟的Multipolynomial结构是的

PS: please note that managed analogue for Multipolynomial struct is class

推荐答案

MSDN < /一个>:P /调用不能具有非blittable型作为返回值。这就是为什么你得到你所得到的错误。此外,您管理的定义不匹配您的非托管的定义。非托管输出包含 multipolynomial 按价值,而是你的管理相当于包含它引用(此外,对象引用不blittable )。托管 Multipolynomial 必须是一个结构,并且必须指定 [的MarshalAs(UnmanagedType.Struct)] MP 字段 - 参见的MarshalAs嵌套结构。另外,我不确定不安全的指针是否blittable。与的IntPtr 替换它们s,而你正在测试这一点,然后把球回。

MSDN: P/Invoke cannot have non-blittable types as a return value. That's why you are getting the error you are getting. Also, your managed definitions don't match your unmanaged definitions. The unmanaged output contains multipolynomial by value, but your managed equivalent contains it by reference (besides, object references are not blittable). The managed Multipolynomial must be a struct, and you must specify [MarshalAs(UnmanagedType.Struct)] on the mp field — see MarshalAs nested structure. In addition, I am unsure whether unsafe pointers are blittable. Replace them with IntPtrs while you are testing this out, then put the pointers back in.

这篇关于嵌套结构解组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆