gpt4 book ai didi

c# - 在 C# 中以结构作为返回值调用 C 函数

转载 作者:太空宇宙 更新时间:2023-11-04 04:57:33 25 4
gpt4 key购买 nike

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

这里是 c dll 的 .h 文件声明:

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


Point myFuncs();

现在我想在 C# 中使用这个函数。包装器.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。这里有什么问题?

感谢您的帮助!

最佳答案

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

关于c# - 在 C# 中以结构作为返回值调用 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4213447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com