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

时间:2015-01-05 10:34:09

标签: c vb.net dll

我写了这个程序来调用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不正确。

这个问题是什么原因造成的?它有问题吗?还是我的程序问题?

我按照这个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

1 个答案:

答案 0 :(得分:2)

您可能在调用约定时遇到问题。 DLL可能具有__stdcall个函数。您应该将函数指针声明为

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

您的代码中当前发生的事情是堆栈损坏,因为调用约定不匹配。