C# 以struct作为C中的返回值调用C函数

C# 以struct作为C中的返回值调用C函数,c#,c,struct,invoke,C#,C,Struct,Invoke,我只想从C中的DLL调用一个C函数。这个C函数返回一个结构 下面是c dll的.h文件声明: typedef struct t_Point{ int x; int y; } Point; Point myFuncs(); 现在我想在C.Wrapper.cs中使用此函数: using System.Text; using System.Runtime.InteropServices; namespace CSharp_mit_OpenCV { [StructLayout(Lay

我只想从C中的DLL调用一个C函数。这个C函数返回一个结构

下面是c dll的.h文件声明:

typedef struct t_Point{
 int x;
 int y;
} Point;


Point myFuncs();
现在我想在C.Wrapper.cs中使用此函数:

using System.Text;
using System.Runtime.InteropServices;

namespace CSharp_mit_OpenCV
{
    [StructLayout(LayoutKind.Sequential)]
    public struct Point
    {
        public int x;
        public int y;
    };

    class Wrapper
    {
        [DllImport("OpenCV Test.dll", CharSet= CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Struct)]
        public static extern Point myFuncs();
    }
}
用法如下:

Point p = Wrapper.myFuncs();
命名可能不是最好的

myFuncs只声明一个结构,将一些值放入x和y并返回它。问题是:我在C中得到的值与在C函数中生成的值不同。它应该是4和2,它是0和111226272。这里有什么问题


谢谢你的帮助

您的marshall代码似乎是正确的,非托管方法的包布局是什么?LayoutKind.Sequential将把您的整数视为4字节。检查这是否正确。

猜测这是类型不同的原因:尝试使用C short而不是int,然后尝试使用uint或ushort。在C尝试从进程输出的字节创建结构之前,您是否可以发布这些字节?它总是返回111226272还是每次的数字都不同?不要忘记确保调用约定是正确的cdecl/fast call,等等。请参见此处: