c# - 我正在尝试将结构从 C 编码到 C#,但不确定从哪里开始

标签 c# c marshalling

我在 C++ 中的结构如下

 /* this structure contains the xfoil output parameters vs angle of attack */
    typedef struct xfoil_outputdata_struct
    {
     double *pAlfa;
     double *pCL;
     double *pCM;
     double *pCDi;
     double *pCDo;
     double *pCPmax;
     long nEntries;
    } XFOIL_OUTPUT_DATA;

    /* Here are the function prototypes for XFoil */
    __declspec(dllexport) XFOIL_OUTPUT_DATA *xfoilResults(); /* get output from xfoil */

我使用 XFoilResults 将该结构拉回到 C# 中

我的 DLL 导入语句如下:

 [DllImport("xfoilapi.dll")]
        public static extern void xfoilResults();

这是正确的吗?我无法控制 C++ 代码。我只需要能够将结构拉入 C#。到目前为止,我拥有的 C# 结构如下

[StructLayout(LayoutKind.Sequential)]
    public  struct xfoilResults
    {
     IntPtr pAlfa;
        IntPtr pCL;
        IntPtr pCM;
        IntPtr pCDi;
        IntPtr pCDo;
        IntPtr pCPmax;
     long nEntries;
    }

如何使用 C++ 代码中的数据填充此 C# 结构?

最佳答案

StructLayout 必须在一个类上。

这应该可以解决问题:

[DllImport("xfoilapi.dll")]
public static extern IntPtr GetXfoilResults();

[StructLayout(LayoutKind.Sequential)]
public class XfoilResults
{
    IntPtr pAlfa;
    IntPtr pCL;
    IntPtr pCM;
    IntPtr pCDi;
    IntPtr pCDo;
    IntPtr pCPmax;
    int nEntries; // thanks to guys for reminding me long is 4 bytes
}

XfoilResults xf  ==  new XfoilResults();
Marshal.PtrToStructure(GetXfoilResults(), xf);

关于c# - 我正在尝试将结构从 C 编码到 C#,但不确定从哪里开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4464532/

相关文章:

c# - 如何在内容中实现文本文件 (XNA)

使用 printf 参数的变量调用 printf、snprintf、f_printf 等

c# - 此 C# 结构是否保证具有所需的大小?

c# - 如何从 C# 中的字符串中删除带引号的字符串文字?

c# - 如何用派生类序列化基类

c# - 如何使用 Twincat3 启动/重启 PLC(错误 1793)

c - K&R :C - Stack smashing detected

c - 是否可以在 C 中使用事件总线?

json - easyjson 将数组解码为 go 结构

c# - C# 中的编码(marshal)处理 - 将指针传递给结构 ("double ref"的引用?)