C#-同步调用C DLL函数

问题描述

我正在尝试使用C#中的参数调用C#中的dll函数,该参数在文档中被称为“ ...如果传递了pfn = NULL,则该调用是同步的。”。我实际上是将NULL(IntPtr.Zero)传递给它,因此该方法应称为同步。现在,当我调用方法时,我一直都收到“ FatalExecutionEngineError”错误代码0xc0000005,并且我认为同步是问题所在。

所以我的问题是:如何在C#中同步调用C DLL方法?还是该方法需要回调函数

该dll来自西门子WinCC运行系统,有关方法的文档在这里(GetFocus方法在第1923页):https://cache.industry.siemens.com/dl/files/216/109755216/att_940522/v1/WCC_PReference_en-US.pdf?download=true

dll导入:

[DllImport("PDLRTAPI.dll",EntryPoint = "PDLRTGetFocusW",CharSet = CharSet.Unicode,CallingConvention = CallingConvention.Winapi)]
        public static extern bool PDLRTGetFocus([In] UInt16 adrMode,[In,Out] ref FOCUSINFO pFocusInfo,Out] IntPtr pfn,Out] IntPtr pvUser,Out] [MarshalAs(UnmanagedType.LPStruct)]
                                                       CMN_ERROR_MANCLASS pError);

方法调用

pdlrtapiDLLWrapper.FOCUSINFO focusinfo = new pdlrtapiDLLWrapper.FOCUSINFO();
            bRet = pdlrtapiDLLWrapper.PDLRTGetFocus((UInt16)1,ref focusinfo,IntPtr.Zero,err);

C#中的FOCUSINFO的结构

[StructLayout(LayoutKind.Auto,CharSet = CharSet.Unicode)]
        public class FOCUSINFO
        {
            [MarshalAs(UnmanagedType.ByValTStr,SizeConst = 256)]
            public string szPicture;
            [MarshalAs(UnmanagedType.ByValTStr,SizeConst = 256)]
            public string szObject;
        }

PDLRTAPI.h中FOCUSINFO的结构

typedef struct tagFOCUSINFOW
{
    WCHAR           szPicture[256];
    WCHAR           szObject[256];
} FOCUSINFOW,*LPFOCUSINFOW;

ADRMODE的typedef为:

typedef     unsigned short  ADRMODE;

解决方法

更新:

事实证明,FOCUSINFO参数仅是“ out”参数,而不是“ reference”。 所以正确的代码是:

[DllImport("PDLRTAPI.dll",EntryPoint = "PDLRTGetFocusW",CharSet = CharSet.Unicode,CallingConvention = CallingConvention.Winapi)]
        public static extern bool PDLRTGetFocus([In] UInt16 adrMode,[Out] FOCUSINFO pFocusInfo,[In,Out] IntPtr pfn,Out] IntPtr pvUser,Out] [MarshalAs(UnmanagedType.LPStruct)] CMN_ERROR_MANCLASS pError);

因此对于遇到此问题的每个人:两次检查参数,尤其是dll函数的数据类型...

无论如何,感谢所有试图帮助我的人。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...