System.AccessViolationException:尝试在C ++ dll中读取或写入受保护的内存

时间:2015-10-08 03:18:32

标签: c++ vb.net dll access-violation

所以我一直在摸不着头脑。我已经构建了一个在VB.net项目中使用的C ++ DLL。 C ++源代码如下所示。

C ++

    #include "stdafx.h"
    #include "mydll.h"
    #include <vector>
    #include <string>
    #include <algorithm>
    #include <sstream>
    #include <fstream>
extern "C" __declspec(dllexport) void __cdecl ExtractVolumeDataC(std::string path, std::string fileName, bool chkVol, std::string txtKeyName)
{

    std::string line;
    std::vector<std::vector<std::string>> ValuesCSV;
    std::replace(path.begin(), path.end(), '\\', '/'); //replace backslash with forward slash
    std::ifstream in(path + fileName);
    while (std::getline(in, line)) {
    std::string phrase;
    std::vector<std::string> row;
    std::stringstream ss(line);
    while (std::getline(ss, phrase, ',')) {
    row.push_back(std::move(phrase));
    }
    ValuesCSV.push_back(std::move(row));
    }
}

我在VB.net中使用的代码如下

VB.net

    Public Class Form1

    <Runtime.InteropServices.DllImport("mydll.dll")> _
    Public Shared Sub ExtractVolumeDataC(ByVal path As String, ByVal fileName As String, ByVal txtKeyName As String)

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ExtractVolumeDataC("C:\\users\me\\documents\\", "VOL.CSV", "01100872")
    End Sub
End Class

我做的一个观察是我没有使用基元来获得此错误,但包括stringvector等STL元素。我收到了错误。我很抱歉,如果这个愚蠢的问题我在15年内没有看过C ++代码。

2 个答案:

答案 0 :(得分:0)

VB.net不会将字符串作为c ++传递std::stringByVal字符串作为指向chars(即旧C样式字符串)的指针传递。您可以使用LPCSTR作为参数类型。在你的情况下,这将是:

extern "C" __declspec(dllexport) void __cdecl ExtractVolumeDataC(LPCSTR path, LPCSTR fileName, bool chkVol, LPCSTR txtKeyName)

有关详细信息,请参阅This Microsoft support page

答案 1 :(得分:0)

您不能在dll中使用STL元素。它们未从dll明确导出。最好的方法是始终在DLL中使用C样式代码导出函数。

这里是关于在dll中使用的STL的答案。

returning std::string/std::list from dll