如何构建非托管函数,只需获取类输入并返回类输出?

时间:2013-10-04 14:12:38

标签: c# marshalling

我有不安全的班级Multipolynomial

[StructLayoutAttribute(LayoutKind.Sequential)]
public unsafe class Multipolynomial
{
    private int _n;
    private int _max_power;

    //get/set code below for _n and _max_power
    ...

    public double* X { get; set; }
    public double** Y { get; set; }
}

我有两个类只包含双精度和多重多项式属性:

[StructLayoutAttribute(LayoutKind.Sequential)]
public unsafe class Input
{
    public double S_M { get; set; }
    public Multipolynomial C_x_M { get; set; }
    ...
    public Input()
    {
        C_x_M = new Multipolynomial();
        ...
    }
}

[StructLayoutAttribute(LayoutKind.Sequential)]
public unsafe class Output
{
    //very same as Input
    ...
}

并且函数dummy_solution具有非托管签名

KERNEL_API output dummy_solution(input *in_p);  //input and output are unmanaged structs

并管理签名

[DllImport("kernel.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern Output dummy_solution(Input in_p);

问题是我试图执行代码

Input input = new Input();
Output output = new Output();
MathKernel.no_solution(input);  //works great except it does nothing and returns nothing =P
output = MathKernel.dummy_solution(input);  //does nothing, simply returns empty Output object and crashes

它抛出异常XamlParseException,内部异常为{"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."}

no_solution函数只是具有非托管签名的虚拟测试函数

KERNEL_API void no_solution(input *in_p);

并管理签名

[DllImport("kernel.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void no_solution(Input in_p);

因此我得出结论,返回Output对象有问题。 老实说,对于像编组这样可怕的东西,我可能会有一些丑陋的傻瓜,我看不到。

请指出什么错误或提出建议如何构建非托管函数,只需获取类输入并返回类输出

1 个答案:

答案 0 :(得分:0)

PInvoke不能将非blittable类型作为返回值。 最简单的方法是创建所有类结构。

Nested struct unmarshalling