我有一个C DLL,它定义了一个结构和一个带有指针的函数:
标题
typedef struct {
double arr[10];
double anotherParam;
double result;
} CStruct_t;
int __stdcall CFunction(CStruct_t * c_struct);
源:
int __stdcall CFunction(CStruct_t * c_struct) {
double sum = 0.0;
for (int i = 0; i < 10; ++i) {
sum += c_struct->arr[i];
}
c_struct->result = sum * c_struct->anotherParam;
}
我可以在C中正确使用DLL:
CStruct_t my_struct = {{0,1,2,3,4,5,6,7,8,9}, 2, 0};
CFunction(&my_struct);
printf("Result = %f ", my_struct.result);
但是,我想在Excel中使用它。因此,我在VBA中试过这个:
Private Declare Function CFunction Lib "cstruct.dll" (ByRef c_struct As CStruct_t) As Long
Type CStruct_t
arr(10) As Double
anotherParam As Double
result As Double
End Type
Sub TryCStruct()
Dim prev_path As String
prev_path = CurDir
ChDir ThisWorkbook.Path
Dim cs As CStruct_t
For i = LBound(cs.arr) To UBound(cs.arr)
cs.arr(i) = i
Next
cs.anotherParam = 2
MsgBox "Retval =" & CFunction(cs)
MsgBox "Result = " & cs.result
ChDir prev_path
End Sub
但是尽管工作,它返回不正确的结果(42988244而不是90)。我认为这是因为VBA数组是SAFEARRAY而不是C之类的固定大小,但是this page让我觉得固定大小的数组也应该固定在内存中。
无论如何,我已经看到了将指针传递给数组中数据的示例,但是在使用混合类型时我找不到任何内容。
有没有办法在VBA中正确分配内存并将结构指针传递给DLL,或者我必须以某种方式在C中管理它或者将每个数组元素声明为结构的成员并忘记在VBA中轻松编制索引?
答案 0 :(得分:2)
VBA声明应为:
?Extract
VBA中数组声明中的数字是数组的上限(基数0), 不 C中的元素数。在VBA中,{ {1}}相当于C中的Type CStruct_t
arr(9) As Double
anotherParam As Double
result As Double
End Type
。
强制性演示代码:
arr(10) As Double