无法在DLL中调用函数

时间:2012-12-04 09:34:25

标签: c++ winapi dll

无法调用在SCALE文件夹中的DLL“sdm00.dll”。我试图调用“SpC”函数,该函数将参数作为“数字”转换为asci代码+“SpApp |”。但是我能够加载DLL&调用function.PLZ帮助

#include <windows.h>  
#include <stdio.h>  
#include <iostream>  

using namespace std;  
typedef string (__cdecl *MYPROC)(string);   

char asc(int a)
{  
    char var;  
    var = (char)a; 
    return var;  
}  

int main()   
{   
    char z;  
    z = asc(20);     
    string str1;  
    string str2;  
    string str3;  
    string retval;     
    str1 = z;  
    str2 = "SpApp|";  
    str3 = str1 + str2;  

    HINSTANCE hinstLib;   
    MYPROC ProcAdd;   
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;  

    // Get a handle to the DLL module

    hinstLib = LoadLibrary(TEXT("c:\\SCALE\\sdm00.dll"));   

    //If the handle is valid, try to get the function address

    if (hinstLib != NULL)   
    { 
        ProcAdd = (MYPROC) GetProcAddress(hinstLib, "SpC"); 

        // If the function address is valid, call the function.

        if (NULL != ProcAdd) 
        {
            fRunTimeLinkSuccess = TRUE;
            cout << "Function is called" << endl;
            string MyRetValue;
            MyRetValue = (string)(ProcAdd)(str3); 
            cout << MyRetValue << endl;
        }
        else
        {
            cout << "Function cannot be called" << endl;
        }

        // Free the DLL module.

        fFreeResult = FreeLibrary(hinstLib); 
    } 

    // If unable to call the DLL function, use an alternative.
    if (!fRunTimeLinkSuccess) 
        printf("Message printed from executable\n"); 

    std::cin.get();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

如果DLL在Delphi中可以正常使用,那么它绝对不会将std::string作为输入或返回std::string作为输出,因为Delphi没有std::string的概念。更有可能的是,该函数实际上以char*作为输入并返回char*作为输出(如果它取而代之的是Delphi String作为输入并返回Delphi String作为输出,那么你是SOL),例如:

#include <windows.h>  
#include <stdio.h>  
#include <iostream>  

typedef char* (__cdecl *MYPROC)(char*);   

int main()   
{   
    HINSTANCE hinstLib = LoadLibrary(TEXT("c:\\SCALE\\sdm00.dll"));   
    if (hinstLib == NULL)   
    {
        cout << "Unable to load sdm00.dll! Error: " << GetLastError() << std::endl;
    }
    else
    { 
        MYPROC ProcAdd = (MYPROC) GetProcAddress(hinstLib, "SpC"); 
        if (NULL == ProcAdd) 
        {
            cout << "Unable to load SpC() function from sdm00.dll! Error: " << GetLastError() << std::endl;
        }
        else
        {
            std::string str1 = char(20);  
            std::string str2 = "SpApp|";  
            std::string str3 = str1 + str2;  
            std::string retval = ProcAdd(str3.c_str()); 
            std::cout << retval << std::endl;
        }

        FreeLibrary(hinstLib); 
    } 

    std::cin.get();
    return 0;
}