【问题标题】:C# calling C++ dll attempts to read or write protected memoryC# 调用 C++ dll 尝试读取或写入受保护的内存
【发布时间】:2014-03-16 15:26:37
【问题描述】:

我正在尝试使用 DLL 中的函数,但我不断得到一个 XamlParseException,但我能够在逐步运行我的程序时看到我得到一个 AccessViolationException,我认为这是原因第一个例外。
基本上,该功能应该做的是将我登录到程序的目录以使用不同的类与程序进行交互。
我无法访问 DLL 的源代码,但我有一些文档可以使用它,即使其中没​​有很多信息,我应该如何使用它:

    Logon(BSTR DirectoryPath, BSTR ErrorFile, int Lang)

这是我的代码:

public partial class MainWindow : Window
{
    [DllImport("kernel32.dll")]
    static extern IntPtr LoadLibrary(string dllToLoad);

    [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

    [UnmanagedFunctionPointer(CallingConvention.Winapi)]
    private delegate int Logon([MarshalAs(UnmanagedType.BStr)]String DirectoryPath, [MarshalAs(UnmanagedType.BStr)]String ErrorFile, int Lang);

    public MainWindow()
    {
        InitializeComponent();

        try
        {

            string LnkPsbEppPath = "dll/LnkPsbEpp.dll";
            IntPtr pAddressFctLogon = GetProcAddress(LnkPsbEppLink, "@Tdtm_Dossier@Logon$qv"); 
            if (pAddressFctLogon == IntPtr.Zero)
                Console.WriteLine("Logon function not found");
            else
            {   
                try
                {
                    dynamic logon = Marshal.GetDelegateForFunctionPointer(pAddressFctLogon, typeof(Logon));
                    dynamic varLogon = logon(directoryPath, errorFilePath, 2); // <-- Here is where the AccessViolactionException happend
                }
                catch (Exception ex)
                {

                }
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine("ERROR : " + ex.Message);
        }

    }
}

【问题讨论】:

  • 顺便说一下,在这个DLL附带的文档中,指定如果你使用Logon,如果它还没有完成,它将自动尝试连接到SQL Server。这可能是AccessViolationException 的原因吗?
  • 你设法让它工作了吗?你介意与世界(或至少我)分享你的知识吗?我实际上和你有完全相同的问题。我基本上是在尝试实现完全相同的目标......专家/M 真是太痛苦了

标签: c# c++ exception visual-studio-2012 dll


【解决方案1】:

检查 C++ dll 是否为你提供了写权限。

查看 C++ dll 文档了解更多详情

即使我在 WPF 应用程序中使用 C++ dll 时也遇到了同样的问题

【讨论】:

    【解决方案2】:

    如果在非托管代码中访问了一些 Null 指针,则可能会发生这种情况。

    【讨论】:

      猜你喜欢
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      相关资源
      最近更新 更多