Delphi DLL called from C++ crashes when showing a form -
edit: dumb question, fixed. form1
nil
because didn't assign new tform1
, forgot delphi doesn't c++.
i have delphi dll want use gui of c++ program, starters, created form, , have function show form exported c++ can call it. however, program crashes when calls function. here code. (i using delphi 2010)
the delphi part:
unit main; interface uses windows, messages, sysutils, variants, classes, graphics, controls, forms, dialogs, tabs, comctrls; type tform1 = class(tform) tabcontrol1: ttabcontrol; tabset1: ttabset; private { private declarations } public { public declarations } end; var form1: tform1; function showform(i: integer) : integer; export; cdecl; exports showform name 'showform'; implementation {$r *.dfm} function showform(i: integer) : integer; export; cdecl; begin form1.show(); result := 3; // random value, doesn't mean end; end.
and here c++ code:
hmodule h = loadlibrary("delphidll.dll"); if (!h) { printf("failed loadlibrary (getlasterror: %i)\n", getlasterror()); return 0; } farproc p = getprocaddress(h, "showform"); if (p) printf("found @ %p\n", p); else printf("didn't find it\n"); ((int(__cdecl *)(int))p)(34); system("pause"); return 0;
the program prints "found @ " , crashes. if comment out form1.show()
in delphi dll, doesn't crash, , function returns 3 (tested printf). missing initialization or something? thanks.
the reason crases var form1: tform1;
not initialized.
the reason var form1: tform1;
not initialized, because put unit main
dll project, came delphi vcl project had form1
on auto-creation list.
the auto-creation list means delphi .dpr initialize form.
now need manually create form, need export these 3 new routines dll, , have c++ dll call them:
function createform() : integer; export; cdecl; begin try application.createform(tform1, form1); result := 0; except result := -1; end; end; function destroyform() : integer; export; cdecl; begin try if assigned(form1) begin freeandnil(form1); application.processmessages(); end; result := 0; except result := -1; end; end; function destroyapplication() : integer; export; cdecl; begin try freeandnil(application); result := 0; except result := -1; end; end;
in addition, should put try...except
block around implementation of showform
function implementation, exceptions , other language dependent run-time features should not cross dll boundaries.
you should similar things releasing other potentially allocated pieces of dynamic memory too.
--jeroen
Comments
Post a Comment