2

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;
juergen d
  • 201,996
  • 37
  • 293
  • 362
  • Try [this similiar thread][1], hope it helps. [1]: http://stackoverflow.com/questions/1244441/accessviolation-when-using-c-dll-from-delphi – CloudyMarble Oct 21 '11 at 09:39
  • 2
    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 Oct 21 '11 at 10:04

3 Answers3

7

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.

Heinrich Ulbricht
  • 10,064
  • 4
  • 54
  • 85
0

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
-1

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

minimum enum size:  double word
record field alignment:  quad word
X-Ray
  • 2,816
  • 1
  • 37
  • 66