c++ - 请帮助我将这个结构数组编码为 C++

标签 c++ marshalling com-interop

C++ 代码:

  typedef struct {
    int bd_number;                      // number of boardset
    int bd_copies;                      // how many copies
    int bd_reserve;                     // only allocate if needed
} bd_t,*bd_p;

typedef struct boardset_info {
    int     bs_copies;          
    int     bs_demand;          
    int     bs_allocated;       
    int     bs_ontable_avail;       
    int     bs_ontable_needed;      
    pstatus bs_status;              
    int     bs_played_sofar;        
} bsi_t, *bsi_p;

FC_ERRORCODE dropin_boards(bd_p boards) {
    int bs;

    bs_info = (bsi_p) calloc(total_boardsets+1, sizeof(bsi_t));//total_boardsets=8
    for (bs = 1; bs <= total_boardsets; bs++)
        bs_info[bs].bs_status = PS_OUTPLAY;

    while (boards->bd_number) { //boards-<bd_number is betweeen 1 and 8
        if (boards->bd_number < 0 || boards->bd_number > total_boardsets)
        {
            debprint("***Error dropin_boards***\n");
            debprint("boardsetnumber=%d\n",boards->bd_number);
            return FC_ERR_PARAM;
        }
        //code does not reach this point
    }

调用代码:

<StructLayout(LayoutKind.Sequential)>
Public Structure Flex_BoardSetInfo
    Public SetNumber As Integer
    Public Copies As Integer
    Public IsReserve As Integer
End Structure

<DllImport("FlexCalc2.dll", CallingConvention:=CallingConvention.StdCall)>
    Public Shared Function FlexCalcBoards(ByRef boards() As Flex_BoardSetInfo) As Flex_ErrorCode
    End Function

Dim boardsets() = GetBoardSetInfo() // creates an arry of 8 BoardsetInfo Elements

_result = FlexCalcWrapper.FlexCalcBoards(boardsets) 

调试文件的最后一行记录了 bd_p->board_number=517237496!板号初始化为 1 到 8,我可以在代码传递到 C++ dll 之前检查是否已正确完成。 我该如何解决这个问题?

编辑: 从 VB6 开始,我们使用 hack 来让这个 C++ 方法工作:

Declare Function FlexCalcBoards Lib "FlexCalc2.dll" (firstBoard As BoardsetInfo)
ret=FlexCalcBoards(Boards(0))

因此,我们传递了数组的第一个元素,而不是数组本身! (嗯?)幸运的是,Net 并没有落入这个陷阱......

最佳答案

将 ByRef 替换为 ByVal。数组已经被编码为指针。

使用 ByRef 只会匹配 C 端的 bd_t**

关于c++ - 请帮助我将这个结构数组编码为 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10351068/

相关文章:

c++ - 从 utf 8 混合中分离繁体中文字符

c# - 编码变量参数 - __arglist 或替代

使用 VB.NET 调用带有字符指针的非托管 C DLL

.net - 如何判断 Excel 应用程序是否处于单元格编辑模式?

c++ - noexcept(false) 析构函数覆盖所有特殊成员函数的异常规范?

c++ - C++ 中指针的困难/链接错误

json - 覆盖 json.Marshal 使用的布局来格式化 time.Time

c# - 在 C# 中动态加载和使用 COM 对象

c# - 应用程序退出后仍保留在内存中

C++:是否可以使用带有模板参数的动态绑定(bind)?