I have a DLL function and I want this function to return an array of integers.
My function definition is as follows:
extern "C" void HelloWorldArray(int * &A) {
std::vector<int> *pVectorA = new std::vector<int>;
pVectorA->push_back(2);
pVectorA->push_back(4);
pVectorA->push_back(8);
pVectorA->push_back(16);
pVectorA->push_back(32);
A = pVectorA->data();
}
As far as I know, this effectively returns the address of the vector which in C++ guarantees that it can be exchanged by the address of an equivalent array because vector guarantees contiguous memory location. I have also read that using new for the vector stores both vector header and vector data in the heap and hence can be consumed outside the function.
In VB.NET I try this:
Imports System.Runtime.InteropServices
Public Class Form1
<DllImport("dll.dll", CallingConvention:=CallingConvention.Cdecl)>
Private Shared Function HelloWorld(ByVal x As Int32) As Int32
End Function
Private Declare Function HelloWorld Lib "dll.dll" (int) As Integer
Private Declare Function HelloWorldArray Lib "dll.dll" (int())
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim j As Integer()
HelloWorldArray(ByRef j as Integer())
Console.WriteLine(j)
End Sub
End Class
Which does not even compile, it gives BC30201 Expression expected. for line Private Declare Function HelloWorldArray Lib "dll.dll" (int()).
Any tips on how to return an array of an unknown length from C++ to VB.NET is welcomed.
Note: the array needs to be passed by reference in the arguments, not as return element, because in the real application several arrays need to be moved back to VB.NET.
I am using Visual Studio 2017.