为什么调用 dll 函数会改变我在 C 中的变量?

Why calling dll function will change my variable in C?

我写这个程序是为了调用 dll 中的一些函数。

一切正常,直到函数接受指针参数。

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <windows.h>

typedef uint32_t (*rf_init_com)(uint32_t,uint32_t);
typedef uint32_t (*rf_halt)(uint32_t);
typedef uint32_t (*rf_request)(uint16_t, uint8_t, uint16_t*);

int main()
{
    HINSTANCE masterRD = LoadLibrary("MasterRD.dll");
    rf_init_com rf_init_com_function =(rf_init_com) GetProcAddress(masterRD, "rf_init_com");
    rf_halt rf_halt_function =(rf_halt) GetProcAddress(masterRD, "rf_halt");
    rf_request rf_request_function =(rf_request) GetProcAddress(masterRD, "rf_request");


    uint32_t initResult= rf_init_com_function(3,9600);
    printf("init = %d\n",initResult);

    uint32_t haltResult= rf_halt_function(0);
    printf("halt = %d\n",initResult);

    uint16_t tagType=0;
    uint32_t requestResult= rf_request_function(0, 0x52, &tagType);
    printf("request = %d, tag type = %d << first time, value is correct\n",requestResult, tagType);
    printf("request = %d, tag type = %d << second time, value is incorrect\n",requestResult, tagType);
    printf("request = %d, tag type = %d << value is still incorrect\n",requestResult, tagType);
    printf("request = %d, tag type = %d << value is still incorrect\n",requestResult, tagType);
    printf("request = %d, tag type = %d << value is still incorrect\n",requestResult, tagType);
    printf("request = %d, tag type = %d << value is still incorrect\n",requestResult, tagType);



    char *a="abc";
    char *b="xyz";
    printf(a);
    printf(b);
    printf(" << other variable also has problem");


    return 0;
}

我得到了这个输出

init = 0
halt = 0
request = 4, tag type = 4 << first time, value is correct
request = 64, tag type = 64 << second time, value is incorrect
request = 64, tag type = 64 << value is still incorrect
request = 64, tag type = 64 << value is still incorrect
request = 64, tag type = 64 << value is still incorrect
request = 64, tag type = 64 << value is still incorrect
abcabc << other variable also has problem

调用rf_request_function后,requestResulttagType的值是正确的,但是,如果我再次打印它们,值将被改变,所以我不能保留结果的值其他变量也有问题,变量b不正确。

出现这个问题的原因是什么?是dll问题吗?还是我的程序问题?

我按照这个vb例子在我的程序中声明函数,这个例子带有dll文档。

Option Strict Off
Option Explicit On
Module mo_declare
    Public Declare Function rf_init_com Lib "MasterRD.dll" (ByVal port As Integer, ByVal baud As Integer) As Integer

    'int WINAPI rf_halt(unsigned short icdev);
    Public Declare Function rf_halt Lib "MasterRD.dll" (ByVal icdev As Short) As Integer

    'int WINAPI rf_request(unsigned short icdev, unsigned char model, unsigned short *TagType);
    Public Declare Function rf_request Lib "MasterRD.dll" (ByVal icdev As Short, ByVal model As Byte, ByRef TagType As Short) As Integer

End Module

您的调用约定可能有问题。 DLL 可能有 __stdcall 函数。您应该将函数指针声明为

typedef uint32_t (__stdcall *rf_init_com)(uint32_t,uint32_t);
...

您的代码中当前发生的是由于调用约定不匹配导致的堆栈损坏。