繁体   English   中英

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

[英]Marshaling fixed size enum array in C#

我正在尝试在 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,
}

非常感谢。

我制作了一个非常简单的程序来将 enum[] 发送到 C++。 C++ 将读取枚举并将其当前内容写入文件。 现在它不返回任何东西,因为我不知道FtStatus可以是什么。

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;
}

我希望这能让您了解如何做到这一点。

暂无
暂无

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

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