我是C ++的新手,并试图构建一个用于VB.NET(VS2013)项目的DLL。我本质上只是想访问C ++中可用的部分排序函数
我在测试vb项目中创建了一个简单的表单。 我在VC ++(2013)中编译了dll并将其复制到VB代码中指定的目录。
我单击表单上的按钮,然后收到错误消息:
System.Windows.Forms.dll中出现未处理的“System.AccessViolationException”类型异常
附加信息:尝试读取或写入受保护的内存。这通常表明其他内存已损坏。
我怀疑(因为我真的不知道我在用指针做什么),vb代码几乎肯定是不正确的。
任何帮助表示感谢。
C ++代码:
CPartialSort.h
extern "C" __declspec(dllexport) double* PSort(double* vArr, int Arrlength, int SortLength);
CPartialSort.cpp
#include "stdafx.h"
#include "CPartialSort.h"
#include <array>
#include <vector>
double* PSort(double* vArr, int Arrlength, int SortLength)
{
int i;
std::vector<double> myvector(vArr, vArr + Arrlength);
// using default comparison (operator <):
std::partial_sort(myvector.begin(), myvector.begin() + SortLength, myvector.end());
//reuse vArr
for (i = 0; i < Arrlength; i++)
{
vArr[i] = myvector[i];
}
return vArr;
}
VB.NET代码:
Imports System.Runtime.InteropServices
Dll功能
<DllImport("CPartialSort.dll", CallingConvention:=CallingConvention.Cdecl)> _
Public Shared Function PSort(ByRef vArr() As Double, _
ArrayLength As Integer, SortLength As Integer) As Double
End Function
表单上的按钮运行以下代码。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dllDirectory As String = "C:\Users\user1\Documents\Visual Studio 2013\Projects\WindowsApplication1"
Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + ";" + dllDirectory)
Dim testarray(10) As Double
For i = 0 To 9
testarray(i) = 10 - i
Next
Dim thepointer As IntPtr = PSort(testarray, testarray.Length, 5)
Dim thedouble As Double() = New Double(0) {}
Marshal.Copy(thepointer, thedouble, 0, testarray.Length)
MsgBox(thedouble(0))
End Sub