系统.AccessViolationException:试图在c++ dll中读写受保护的内存

System.AccessViolationException : Attempted to read or write protected memory in C++ dll

本文关键字:读写 受保护 内存 dll c++ AccessViolationException 系统      更新时间:2023-10-16

所以我一直在挠我的头一段时间。我已经建立了一个c++ dll在VB.net项目中使用。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:\usersme\documents\", "VOL.CSV", "01100872")
    End Sub
End Class

我所做的一个观察是,我没有得到这个错误的原语,但包括STL元素,如stringvector。我得到了错误。如果这是一个愚蠢的问题,我很抱歉,我已经有15年没有看过c++代码了。

VB.net不传递字符串作为c++ std::string, ByVal字符串作为指针传递到字符(即旧的c风格字符串)。您可以使用LPCSTR作为参数类型。在您的例子中,这将是:

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

不能在dll中使用STL元素。它们没有显式地从dll中导出。最好的方法是在DLL中导出函数时始终使用C风格的代码。

这里有一个关于STL在dll中使用的回答。

从dll返回std::string/std::list