C++ System.AccessViolationException:试图读取或写入C+中的受保护内存+;动态链接库
所以我对这件事挠头已经有一段时间了。我在VB.NET项目中构建了一个C++ DLL。C++源代码如下所示。 C++C++ System.AccessViolationException:试图读取或写入C+中的受保护内存+;动态链接库,c++,vb.net,dll,access-violation,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>
#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));
}
}
#包括“stdafx.h”
#包括“mydll.h”
#包括
#包括
#包括
#包括
#包括
外部“C”uuu declspec(dllexport)void uuu cdecl extractedvolumedatac(std::string path,std::string fileName,bool chkVol,std::string txtKeyName)
{
std::字符串行;
std::向量值scsv;
std::replace(path.begin()、path.end()、“\\”、“/”);//将反斜杠替换为正斜杠
std::ifstream-in(路径+文件名);
while(std::getline(in,line)){
字符串短语;
std::向量行;
std::stringstream ss(线路);
while(std::getline(ss,短语,,')){
行。推回(标准::移动(短语));
}
值csv.推回(标准::移动(行));
}
}
我在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
公共类表单1
_
公共共享子提取VolumeDatac(ByVal路径作为字符串,ByVal文件名作为字符串,ByVal txtKeyName作为字符串)
端接头
私有子按钮1\u单击(发送者作为对象,e作为事件参数)处理按钮1。单击
ExtractVolumeDataC(“C:\\users\me\\documents\\”、“VOL.CSV”、“01100872”)
端接头
末级
我所做的一个观察是,我没有在原语中得到这个错误,但是包含了STL元素,比如
string
和vector
。我得到了错误。很抱歉,如果这个愚蠢的问题我没有在15年内看一个C++代码。< /P> < P> VB.net没有把字符串作为C++ +<代码:ST::String < /C> >,<代码> ByVal < /Cord>字符串作为指针指向字符(即旧的C风格字符串)。您可以使用LPCSTR
作为此操作的参数类型。在您的情况下,这将是:
extern "C" __declspec(dllexport) void __cdecl ExtractVolumeDataC(LPCSTR path, LPCSTR fileName, bool chkVol, LPCSTR txtKeyName)
有关详细信息,请参阅。您不能在dll中使用STL元素。它们不是从dll显式导出的。最好的方法是总是使用C风格的代码在DLL中导出函数 这里有人回答了关于在dll中使用STL的问题