通过DllImport调用非托管函数时,堆已损坏

J_C*_*COL 5 c# c++ pinvoke dllimport visual-studio-2013

我正在使用从C#应用程序以C / C ++编写的非托管dll。我对使用dll中的以下功能感兴趣:

    static void StorePath(const std::string& path, wchar_t *out_path,
     int *out_path_length){
      wcslcpy(out_path, c_str_w(path), *out_path_length);
      *out_path_length = path.size();
     }

    int WINAPI BrowseForDirectory(
     int allow_portable, int allow_online,
      wchar_t *t_directory, int *e_directory_length,
       wchar_t *m_directory, int *m_directory_length){
     .
     .
     . //initializing new forms and checking product keys

    StorePath(form->SelectedEDirectory().TopDir(), e_directory,
     e_directory_length);
    StorePath(form->SelectedMDirectory(), m_directory,
     m_directory_length);
    }
Run Code Online (Sandbox Code Playgroud)

头文件:

    #if defined(_WIN32) && !BUILD_WITHOUT_DLLS &&!defined(ECLIPSE_CBUILDER_WORKAROUNDS)
    # if BUILDING_EXPORT_LIBRARY
    #  define EXPORT_DLL __declspec(dllexport)
    # else
    #  define EXPORT_DLL __declspec(dllimport)
    # endif
    #else
    #  define EXPORT_DLL
    #endif

    extern "C" {
        int WINAPI BrowseForDirectory(
         int allow_portable, int allow_online,
          wchar_t *t_directory, int *e_directory_length,
           wchar_t *m_directory, int *m_directory_length)
    }
Run Code Online (Sandbox Code Playgroud)

然后,我尝试通过执行以下操作在我自己的托管C#类库中调用此函数:

    [DllImport("MyDLL.dll", CharSet = CharSet.Ansi)]
    public static extern int BrowseForDirectory(Int32 allowOnline, 
     Int32 allowPortable,
      [MarshalAs(UnmanagedType.LPStr)] StringBuilder eDirectory, 
       ref Int32 eDirLength, 
        [MarshalAs(UnmanagedType.LPStr)] StringBuilder mDirectory, 
         ref Int32 mDirLength);
Run Code Online (Sandbox Code Playgroud)

最后,我试图通过调用C#应用程序来使用它,例如:

    var eDir = new StringBuilder(260);
    var mDir = new StringBuilder(260);
    var eDirLength = eDir.Length;
    var mDirLength = mDir.Length;
    try
    {
        var result = Viewer.BrowseForDirectory(1, 1, eDir, 
         ref eDirLength, mDir, ref mDirLength);
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
Run Code Online (Sandbox Code Playgroud)

但是,我遇到了堆损坏的问题,但是现在由于STATUS_STACK_BUFFER_OVERRUN导致我的应用程序退出-有关嵌入式断点的信息。更改C ++代码不是一种选择。我有适当的参考资料和程序集。

我究竟做错了什么?

Dav*_*nan 2

我看到的问题是您的字符集不匹配。非托管代码以 UTF-16 形式返回文本,但您的 p/invoke 指定 ANSI 编码文本。将 p/invoke 更改为:

[DllImport("MyDLL.dll", CharSet = CharSet.Unicode)]
public static extern int BrowseForDirectory(
    int allowOnline, 
    int allowPortable,
    StringBuilder eDirectory, 
    ref int eDirLength, 
    StringBuilder mDirectory, 
    ref int mDirLength
);
Run Code Online (Sandbox Code Playgroud)

我假设c_str_w()采用 8 位编码字符串并返回指向以 null 结尾的数组的指针wchar_t