在C#中封送固定大小的枚举数组

3
我正在尝试在C#中编排一个固定大小的数组枚举。
以下是C语言中的本地声明:
typedef enum GPIO_Dir
{
    GPIO_OUTPUT =0,
    GPIO_INPUT,
}
GPIO_Dir;
FT4222_STATUS FT4222_GPIO_Init(FT_HANDLE ftHandle, GPIO_Dir gpioDir[4]);

这是代码示例:
GPIO_Dir gpioDir[4];
gpioDir[0] = GPIO_OUTPUT;
gpioDir[1] = GPIO_OUTPUT;
gpioDir[2] = GPIO_OUTPUT;
gpioDir[3] = GPIO_OUTPUT;

FT4222_GPIO_Init(ftHandle, gpioDir);

本机代码没有任何问题。

我没有问题来封装FT_HANDLE。

我尝试了多种选项,但似乎没有什么真正起作用。我一直在尝试多个定义,但都没有成功,例如:

[DllImport("LibFT4222.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern FtStatus FT4222_GPIO_Init(IntPtr ftHandle, [MarshalAs(UnmanagedType.LPArray, SizeConst = 4)] GpioPinMode[] gpioDir);

我一直在努力装饰数组以通过考试。
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
private GpioPinMode[] _gpioDirections = new GpioPinMode[PinCountConst];

GpioPinMode是一个简单的枚举:
internal enum GpioPinMode : int
{        
    Output = 0,
    Input,
}

非常感谢。

我刚学习了关于DLLimport的知识,但是在函数声明中从未见过“MarshalAs”。在我的一个项目中,我使用了一个“struct”,而不是“MarshalAs”,我使用了结构体的名称。 - wes
“nothing is really working” 不是一个有效的问题描述。 - GSerg
1个回答

2
我已经制作了一个非常简单的程序,用于将枚举[]发送到C ++。 C ++将读取枚举并将其当前状态写入文件。目前它不返回任何内容,因为我不知道可能是什么。
C#
internal enum GpioPinMode : int
{
    Output = 0,
    Input,
}

[DllImport("library.dll", EntryPoint = "FT4222_GPIO_Init", CallingConvention = CallingConvention.Cdecl)]
public static extern void FT4222_GPIO_Init(GpioPinMode[] gpioDir);

static void Main(string[] args)
{
    GpioPinMode[] gpioDir = new GpioPinMode[4];

    gpioDir[0] = GpioPinMode.Input;
    gpioDir[1] = GpioPinMode.Input;
    gpioDir[2] = GpioPinMode.Output;
    gpioDir[3] = GpioPinMode.Output;

    FT4222_GPIO_Init(gpioDir);
}

C++

#include "pch.h"
#include <fstream>

#define DllExport extern "C" __declspec(dllexport)

typedef enum GPIO_Dir
{
    GPIO_OUTPUT = 0,
    GPIO_INPUT,
}
GPIO_Dir;

DllExport void FT4222_GPIO_Init(GPIO_Dir gpioDir[4])
{
    std::ofstream myfile;

    myfile.open("File.txt", std::ios::out);

    if (gpioDir[0] == GPIO_INPUT)
        myfile << 0 << ": input" << std::endl;
    else
        myfile << 0 << ": output" << std::endl;

    if (gpioDir[1] == GPIO_INPUT)
        myfile << 1 << ": input" << std::endl;
    else
        myfile << 1 << ": output" << std::endl;

    if (gpioDir[2] == GPIO_INPUT)
        myfile << 2 << ": input" << std::endl;
    else
        myfile << 2 << ": output" << std::endl;

    if (gpioDir[3] == GPIO_INPUT)
        myfile << 3 << ": input" << std::endl;
    else
        myfile << 3 << ": output" << std::endl;
}

我希望这能让您了解如何实现这一点。

你的声明和 OP 的声明唯一的区别就是你删除了 MarshalAs 属性。这有什么帮助吗? - GSerg
@GSerg,我对dllimports和MarshalAs的知识非常有限,上周我第一次尝试了它。所以我不知道我的方法是如何或为什么有效的。我只知道我从来没有在一个函数中直接看到过“MarshalAs”。 - wes
在使用C++中的Dll进行测试后,正确答案就是基本定义,看起来像这样: [DllImport("LibFT4222.dll", CallingConvention = CallingConvention.Cdecl)] public static extern FtStatus FT4222_GPIO_Init(IntPtr ftHandle, GpioPinMode[] gpioDir); - Laurent Ellerbach

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接