简体   繁体   English

在C#中使用struct作为返回值调用C函数

[英]invoke C function with struct as return value in C#

I simply want to call a C function from a DLL in C#. 我只想从C#中的DLL调用C函数。 This C function returns a struct. 此C函数返回一个结构。

Here the .h-file declaration of the c dll: 这是C dll的.h文件声明:

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


Point myFuncs();

Now I want to use this function in C#. 现在,我想在C#中使用此函数。 Wrapper.cs: 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();
    }
}

The usage is as follows: 用法如下:

Point p = Wrapper.myFuncs();

(Naming is probably not the best) (命名可能不是最好的)

myFuncs only declares a struct, puts some values to x and y and returns it. myFuncs仅声明一个结构,将一些值放入x和y并返回它。 The problem: The values I get in C# are different than those generated in the C function. 问题:我在C#中获得的值与在C函数中生成的值不同。 It should be 4 and 2 and it is 0 and 111226272. What's the problem here? 它应该是4和2,分别是0和111226272。这是什么问题?

Thanks for any help! 谢谢你的帮助!

Your marshall code seems correct, what is the pack layout of the unmanaged method? 您的马歇尔代码似乎正确,非托管方法的包布局是什么? LayoutKind.Sequential will treat your ints as 4 byte. LayoutKind.Sequential会将您的int视为4字节。 Check if this is correct. 检查是否正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM