簡體   English   中英

我如何構建一個Type來傳遞給DLL函數,該函數需要一個指向內部數組的結構的指針?

[英]How do I build a Type to pass to a DLL function that takes a pointer to a struct with an array inside?

我有一個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這樣的固定大小的數組,但是此頁面使我認為固定大小的數組也應該固定在內存中。

無論如何,我已經看到了將指針傳遞到數組中數據的示例,但是在使用混合類型時我找不到任何東西。

有什么方法可以在VBA中正確分配內存並將結構指針傳遞給DLL,還是我必須以某種方式在C中進行全部管理,或者將每個數組元素聲明為結構的成員,而忘記在VBA中輕松進行索引?

VBA聲明應為:

Type CStruct_t
    arr(9) As Double
    anotherParam As Double
    result As Double
End Type

VBA中數組聲明中的數字是數組的上限(以0為底), 而不是 C中的元素數。在VBA中, arr(10) As Double等同於double arr[11]; 在C中

強制演示代碼:

Sub Bounds()
    Dim foo As CStruct_t, i As Long
    For i = LBound(foo.arr) To UBound(foo.arr)
        Debug.Print i
    Next
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM