VB、VC混合编程(dll)中数组的传入传出
2008年10月23日星期四21:39
以前用到的神经网络都是在matlab中调的,而项目需要,要写个神经网络的算法,系统主界面是VB写的,在VB中做网络训练速度是不照的,用VB,VC的混合编程,但是一直被VB与Dll之间的数组传递这个难题所困扰,在网上搜了也找不到答案,据说safearray可以解决,但是看了下比较麻烦,在CSDN社区中也没有找到答案,但是社区中一个朋友的指点,给我找到解决问题的方法了。下面总结下共享。
相当于一维的,而在C/C++中数组可以等价数值型数组在VB中其数据是连续存放的,
于指向数组第1个元素的指针。可以用引用的方式把VB中数组的第1个元素的地址传给VC编写的DLL,在DLL中用一个指针来接收,这样就实现了VB到Dll在中数组的传递。从DLL传递数组给VB方法相同,过程相反.
如果是二维数组,则把二维数组按照一维数组的方式传入传出,只是在使用的时候,顺
便把二维数组的行和列数传递即可。
总体思想是这样的。下面看例子。
VC中:
double ioutArrCount) //一维数组的传入传出{ _stdcall OneDimensionArrayTest(double nCount,double *outArr,int*
{
dRes[i]=inArr[i]*2;
}
for(i=0;i<nCount;i++)
{
outArr[i]=dRes[i];
}
*ioutArrCount=iNum;
returndRes[0];
delete[]dRes;
}
void _stdcall TwoDimensionArrayTest(double *inArr,int nRows,intnCols,double *outArr,int* outRows,int *outCols)//二维数组的传入传出
{
double *dRes=new double[nRows*nCols];
int i;
int j;
for(i=0;i<nRows;i++)
{
for(j=0;j<nCols;j++)
{
dRes[nCols*i+j]=inArr[nCols*i+j]*2;
}
}
for(i=0;i<nRows;i++)
{
for(j=0;j<nCols;j++)
{
outArr[nCols*i+j]=inArr[nCols*i+j]*2;
}
}
*outRows=nRows;
*outCols=nCols;
delete[] dRes;
}
EXPORTS LIBRARY
Add@1
darray@2
OneDimensionArrayTest@3
TwoDimensionArrayTest@4
VB中
DeclareFunction OneDimensionArrayTest Lib"D:\在编程序\Dll\VBLoadDll\TestDll.dll"(ByRef inputer As Double, ByVal inLength As Long, ByRef output AsDouble, ByRef outLength As Long) As Double
DeclareFunction TwoDimensionArrayTest Lib"D:\在编程序\Dll\VBLoadDll\TestDll.dll"(ByRef inputer As Double, ByVal inRows As Long, ByVal inCols As Long,ByRef outputer As Double, ByRef outRows As Long, ByRef outCols AsLong)
PrivateSub cmdTest2_Click()
Dim inputer(8) As Double
Dim out(9) As Double
Dim res As Double
Dimm As Long
inputer(0)= 1.2
inputer(1)= 2.3
inputer(2)= 1
res= OneDimensionArrayTest(inputer(0), 9, out(0), m)
MsgBoxCStr(m), vbOKOnly, "一维数组的元素个数"
'MsgBoxCStr(res)
Dimstr As String
Dimi As Integer
Fori = 0 To UBound(out)
str = str + " " + CStr(out(i))
Next
MsgBoxstr, vbOKOnly, "一维数组的元素"
EndSub
Private Sub cmdTest3_Click()
Dim iRows As Integer
DimiCols As Integer
iRows = 3 iCols = 4 Dim inputer() As Double
Dim oRows As Long Dim oCols As Long
Dim i, j As Integer
Fori = 0 To UBound(inputer, 1)
For j = 0 To UBound(inputer, 2)
inputer(i, j) = (i + 1) * (j + 1)
Next
Next
Dim str As String
For i = 0 To UBound(inputer, 1)
For j = 0 To UBound(inputer, 2)
str = str + " "+ CStr(inputer(i, j))
Next
str = str + vbCrLf
Next
MsgBox str, vbOKOnly, "inputer,二维数组的输入"
Call TwoDimensionArrayTest(inputer(0, 0), iRows + 1, iCols + 1, outputer(0, 0), oRows, oCols)
str= ""
'
Fori = 0 To UBound(outputer, 1)
For j = 0 To UBound(outputer, 2)
str= str + " " + CStr(outputer(i, j))
Next
str = str + vbCrLf
Next
MsgBoxstr, vbOKOnly, "outputer,二维数组的输出"
EndSub
笨方法,很简单,但是真的可以用
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- efsc.cn 版权所有 赣ICP备2024042792号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务