2
votes

I want to call a function of a C++ DLL in my Delphi app.
The problem is that i get an access violation. But not while calling my C++ DLL but when I leave the Delphi function in which I do that.

Error message (shortened):
Access violation at 0x7445c9f1: Reading from address 0x00000000.

My C++ method is like that:

extern "C" __stdcall void SetName(LPCTSTR name) {strcpy_s(nameInDll,512,name);};

My Delphi call looks like this:

begin   
   ...
   hDll := LoadLibrary('myCpp.dll');
   SetName := getprocaddress(hDll, 'SetName');
   SetName(pchar(myControl.text));  //  <--- exception NOT here
   ...
end;  // <--- exception here

the funny thing is that it works if I use hard coded text as input for the DLL call like this:

SetName(pchar('myName'));

EDIT:
I missed the __stdcall definition in my C++ DLL. It was defined in an macro. I corrected the C++ method definition above.

After seeing that and your tips I came up with an solution that works:

procedure SetName(s: PChar); stdcall; external 'myCpp.dll';

begin   
   ...
   SetName(pchar(myControl.text));
   ...
end;
3
Try [this similiar thread][1], hope it helps. [1]: stackoverflow.com/questions/1244441/…CloudyMarble
You need to show the declaration of SetName. I bet you have not declared a calling convention, or have declared the wrong calling convention. Your C++ method is most likely using cdecl.David Heffernan

3 Answers

7
votes

Sounds like SetName uses the wrong calling convention, try using cdecl;

Something like this:

var
  SetName : procedure(nameArg: PChar); cdecl;

Otherwise your stack will be messed up.

0
votes

Is the DLL compiled for Ansi or Unicode? LPCTSTR maps to wchar_t* when UNICODE is defined, or to char* otherwise. That affects how you use the DLL in Delphi, where wchar_t* is equivilent to PWideChar and char* is equivilent to PAnsiChar In Delphi.

-1
votes

depending on heavy your work is, in compiler options you may need to set:

minimum enum size:  double word
record field alignment:  quad word