从编组C#和C ++和背部数组:PInvokeStackImbalance [英] Marshalling arrays from C# to C++ and back: PInvokeStackImbalance

查看:139
本文介绍了从编组C#和C ++和背部数组:PInvokeStackImbalance的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我想从C#访问C ++函数。问题是我不断收到PInvokeStackImbalance例外,我不知道为什么。 。一切都正常运行,并为例外检查被关闭时,如预期

I have a C++ function that I'd like to access from C#. The problem is I keep getting PInvokeStackImbalance exceptions and I don't know why. Everything runs fine and as expected when checking for that exception is turned off.

我的C的签名++函数是:

The signature of my C++ function is:

extern "C" double solveQP(
    int32_t n, int32_t mE, int32_t mI,
    double *p_G, double *p_g0,
    double *p_CE, double *p_ce0,
    double *p_CI, double *p_ci0,
    double *p_x)

和我一直在使用访问它是什么:

and what I've been using to access it is:

        [DllImport("libQuadProg.dll")]
        [return: MarshalAs(UnmanagedType.R8)]
        private static extern double solveQP(
            [In, MarshalAs(UnmanagedType.I4)] int n,
            [In, MarshalAs(UnmanagedType.I4)] int mE,
            [In, MarshalAs(UnmanagedType.I4)] int mI,
            [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.R8)] double[] p_G,
            [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.R8)] double[] p_g0,
            [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.R8)] double[] p_CE,
            [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.R8)] double[] p_ce0,
            [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.R8)] double[] p_CI,
            [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.R8)] double[] p_ci0,
            [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.R8)] double[] p_x);



我也只用UnmanagedType.LPArray选项,什么都没有尝试过。我想有关于PInvoke的一个细节,我只是不明白,我会很感激,如果有人指出来。

I've also tried it with just the UnmanagedType.LPArray option and nothing at all. I figure there is one detail about PInvoke that I just do not get and I'd appreciate it if someone pointed it out.

推荐答案

你需要使用的DllImport的CallingConvention财产。因为你没有申报的C函数为__stdcall CDECL这里需要。你不需要[的MarshalAs],您使用的值已经是默认的。因此:

You need to use the DllImport's CallingConvention property. Cdecl is required here since you didn't declare the C function as __stdcall. You don't need [MarshalAs], the values you use are already the default. Thus:

    [DllImport("libQuadProg.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern double solveQP(
        int n, int mE, int mI,
        double[] p_G,
        // etc...
    }

这篇关于从编组C#和C ++和背部数组:PInvokeStackImbalance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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