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.