【问题标题】:How to get interface from C dll to Delphi?如何获得从 C dll 到 Delphi 的接口?
【发布时间】:2022-11-25 10:12:31
【问题描述】:

我有一个用 C 编写的库,我有一个头文件,其中包含 C 接口的描述。DLL 具有获取此接口的功能。如何正确描述并在DELPHI应用程序中获取?

    using DllCallbackClassPtr = void*;
    using DllCallbackFunction = void(*)(const char *, DllCallbackClassPtr);

    #ifdef _WIN32

    #include <Windows.h>

    __interface IXeoma
    {

    public:
        enum ConnectErrorCode {
            OK = 0,
            SERVER_NOT_FOUND,
            WRONG_PASSWORD,
            UNKNOWN
        };

        // return ConnectErrorCode
        virtual int start(const char* connectionString) = 0;
        virtual bool isConnected() = 0;
        virtual void stop() = 0;

        virtual void requestData(const char* request, const char* additionalData, DllCallbackClassPtr classPtr, DllCallbackFunction callbackFunc) = 0;
        virtual const char* getRequestResult(const char* request) = 0;

        virtual void setCameraRenderHandle(const char* previewId, HWND hWnd) = 0;

    };

库已加载,但函数返回 nil。

    type
       IXeoma = interface
         function Start(connectionString: PChar): integer;
       end;

    type
        TCreateXeomaInterface = function() : IXeoma; stdcall;

    var
        Form1: TForm1;
        CreateXeomaInterface: TCreateXeomaInterface;

    implementation

    {$R *.dfm}

    var
        LibraryHandle: THandle;

     procedure TForm1.Button1Click(Sender: TObject);
    var
        XeomaInt: IXeoma;
        i: integer;
    begin
        LibraryHandle := LoadLibrary(PChar('D:\Projects\XeomaSDK\Win32\Debug\xeomaclientdll.dll'));
        if LibraryHandle >= 32 then
        begin
            @CreateXeomaInterface := GetProcAddress(LibraryHandle, 'createXeomaInterface');
        end;
        XeomaInt := CreateXeomaInterface();
        // Here XeomaInt = nil
    end;

【问题讨论】:

  • 您发布的 C 代码不包括 createXeomaInterface。当我们根本看不到它时,我们怎么知道为什么您无法获取它的地址?
  • 此 C 代码有效: HMODULE xeomaDLL = LoadLibraryW(XEOMA_DLL_PATH);如果(xeomaDLL){ FARPROC func = GetProcAddress(xeomaDLL,“createXeomaInterface”);如果 (func) { g_xeoma = reinterpret_cast<IXeoma*>(func()); g_xeoma->start("123:123@localhost:8090"); } }

标签: delphi


【解决方案1】:

C++(不是 C)中的 __interface 和 Delphi 中的 interface 不是一回事,并且彼此不兼容。

C++ 代码中的IXeoma 只是一个普通的类类型,但在 Delphi 中,class 类型是从 TObject 派生的,因此您将不得不使用普通的 record,并将 TCreateXeomaInterface 声明为返回一个指针该记录,例如:

type
  IXeoma = record
    function Start(connectionString: PAnsiChar): integer; cdecl;
    ...
  end;
  IXeomaPtr = ^IXeoma;

type
  TCreateXeomaInterface = function() : IXeomaPtr; stdcall;

...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 2014-02-27
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多