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

本文关键字:获取 输入 输出 返回 函数 何构建 构建 | 更新日期: 2023-09-27 18:34:06

我有不安全的类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 对象有问题。老实说,我对编组这样可怕的事情是新手,所以也许有我看不到的丑陋愚蠢的木思图。

请指出问题所在或给出如何构建非托管函数的建议,该函数仅获取类输入并返回类输出

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

> PInvoke 不能将非 blitable 类型作为返回值。最简单的方法是使所有类都成为结构。

嵌套结构解组