c++ - Delphi 应用程序无法调用简单的 C++ DLL 函数

标签 c++ delphi dll delphi-6

我想编写一个 C++ DLL 并从 Delphi 6 应用程序调用它。我从教程中的简单 HelloWorld 代码开始,尽管它在从 C++ 程序调用时运行良好,但在 Delphi 应用程序中它会导致以下错误消息 Error in Delphi 6 application

MyDll.h

#ifndef _MY_DLL_H_
#define _MY_DLL_H_

#if defined MY_DLL
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif

extern "C"
{
    MYDLL_API int HelloWorld();
}
#endif

MyDll.cpp

#define MY_DLL

#include <windows.h>
#include "MyDll.h"

BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
        case DLL_PROCESS_ATTACH:
        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
            break;
    }
    return TRUE;
}

MYDLL_API int HelloWorld()
{
    return 9;
}

此 Delphi 代码无法调用 DLL

function HelloWorld(): LongInt; cdecl; external 'MyDll.dll' name 'HelloWorld';

虽然以下 C++ 代码可以正常工作

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

typedef int (*HelloWorldFunc)();

int main()
{
    HelloWorldFunc _HelloWorldFunc;
    HINSTANCE hInstLibrary = LoadLibrary("MyDLL.dll");

    if (hInstLibrary)
    {
        _HelloWorldFunc = (HelloWorldFunc)GetProcAddress(hInstLibrary, "HelloWorld");
        if (_HelloWorldFunc)
        {
            std::cout << "HelloWorld result is " << _HelloWorldFunc() << std::endl;
        }
        FreeLibrary(hInstLibrary);
    }
    else
    {
        std::cout << "DLL Failed To Load!" << std::endl;
    }
    std::cin.get();
    return 0;
}

最佳答案

错误是由加载程序在尝试加载可执行文件并解析其依赖项时产生的。该错误意味着加载程序未能执行此操作。

错误代码是 NTSTATUS代码,即 STATUS_INVALID_IMAGE_FORMAT。这几乎总是由于位数不匹配。 32 位主机加载 64 位 DLL,反之亦然。

鉴于 Delphi 7 是 32 位编译器,您的 C++ 编译器很可能是 64 位编译器。您需要使用 32 位编译器编译 C++ 代码,以便从 32 位 Delphi 代码中使用它。

关于c++ - Delphi 应用程序无法调用简单的 C++ DLL 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29110658/

相关文章:

delphi - 返回先前位置时如何避免 TDbgrid 滚动

delphi - 识别鼠标光标下的组件不适用于 TImage 控件

c# - 将一个项目的 DLL 引用引用到另一个项目中

c++ - 将 C++ 函数指针转换为 c 函数指针

c++ - GCC 编译器是否应该对这个涉及 [[fallthrough]] 属性的格式错误的 C++ 代码进行诊断?

德尔福TTreeView : get root node count and root node by index?

c# - BadImageFormatException:尝试在C#中使用C++ DLL文件吗?

c - 在excel-vba中使用DLL

c++ - 如何以编程方式删除 Windows 中损坏的快捷方式

c++ - 跨动态链接库的模板静态类