系统.AccessViolationException:试图在c++ dll中读写受保护的内存
System.AccessViolationException : Attempted to read or write protected memory in C++ dll
所以我一直在挠我的头一段时间。我已经建立了一个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元素,如string
和vector
。我得到了错误。如果这是一个愚蠢的问题,我很抱歉,我已经有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相关文章:
- C++:无法访问声明的受保护成员
- 用C++快速读写文件
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 在一个读写器队列中,我可以用volatile替换原子吗
- 继承和友元函数,从基类访问受保护的成员
- 为什么派生类的好友不能使用受保护的成员?
- C++:为什么无法在派生类中访问受保护的构造函数?
- C++套接字对不读/写父/子
- 如何调试读写器锁的死锁?
- 在两个线程上读/写 64 位,无互斥/锁定/原子
- 公共/私有/受保护是否会更改内存中结构的排列?
- 尝试读/写受保护的内存错误,同时固定 c++ 函数
- 在线程内部函数上使用哪种保护方法(互斥,读写锁.)
- 系统.AccessViolationException:试图在c++ dll中读写受保护的内存
- 试图读写受保护的内存
- 试图读写受保护的内存.这通常表明其他内存已损坏
- allocVector()在C和System中.AccessViolationException:试图读写受保护的内存
- 是否寄存器读/写需要临界区保护
- 系统.AccessViolationException:试图读写受保护的内存