juergen d
juergen d

Reputation: 204924

Call C++ DLL in Delphi app

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;

Upvotes: 2

Views: 3546

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 598279

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.

Upvotes: 0

X-Ray
X-Ray

Reputation: 2846

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

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

Upvotes: -1

Heinrich Ulbricht
Heinrich Ulbricht

Reputation: 10372

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.

Upvotes: 7

Related Questions