简体   繁体   中英

Strange behaviour in Delphi dynamic DLL call

I have the following issue:

I have a DLL written in C++ that accepts input params as * char.

When declaring the DLL by using the Delphi RTL in the following way:

function MyDllCall(aParam: PAnsiChar): Longint; stdcall; external 'MyDllName.dll' name 'MyFunction'

and calling it from within my code:

MyDllCall(PAnsiChar('some text'));

It works perfectly.

When I tried to call it by calling LoadLibrary, GetProcAddress and FreeLibrary like the below code:

procedure DllCall;
type
  TMyDllCall = function(aParam: PAnsiChar): Longint;
var
  aMyDllCall: TMyDllCall;
  libHandle: Integer;
  res: Integer; 
begin
  libHandle := LoadLibrary('MyDLL.dll');
  if libHandle <> 0 then
  begin
    @aMyDllCall := GetProcAddress(libHandle, 'MyDllFunction');
    if @aMyDllCall <> nil then
    begin
      res:= aMyDllCall(PAnsiChar('some text')); << This crashes
      FreeLibrary(libHandle);
    end;
  end;
end;

I believe the issue is somehow related to the string param passed as PAnsiChar. Tried to change the C++ dll source code logging out the params and verified some strange text in the assigned param variable.

Edit: Here follows part of the C++ Dll code:

#include "stdafx.h"

#pragma once  

#define MYDLLLIBRARY_API extern "C" __declspec(dllexport)   

MYLIBRARY_API DWORD WINAPI MyDllFunction(char * dirname);

DWORD WINAPI MyDllFunction(char * dirName){
    return someFunction(dirName);
}

void getFileNames(char * workingDir){

    HANDLE hFind;
    WIN32_FIND_DATAA data;
    char nextfilename[260];
    sprintf(nextfilename, "%s*.jpg", workingDir);
    hFind = FindFirstFileA(nextfilename, &data);
    if (hFind != INVALID_HANDLE_VALUE) {
        do {
            if (strlen(data.cFileName) < 3) continue;
            char tmp[260];
            sprintf(tmp, "%s%s",workingDir, data.cFileName);
            filenames.push_back(tmp);
        } while (FindNextFileA(hFind, &data));
        FindClose(hFind);
    } else{

        exit(0);
    }
}

int MyDllFunction(char* workingDir)
{
    ...
    getFileNames(workingDir);
    ...
}

Am I missing something? Thanks.

Your first definition (the static one) uses stdcall :

function MyDllCall(aParam: PAnsiChar): Longint; stdcall; external Stdcall 'MyDllName.dll' name 'MyFunction';

Your second (dynamic) does not. As that's the one failing, I think it's clear that the missing stdcall is the issue:

type
  TMyDllCall = function(aParam: PAnsiChar): Longint;  // No stdcall here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM