c++ - Passing PChar from Delphi DLL to C -
i having trouble importing delphi dll dynamically. delphi dll function declared here :
function test() : pchar; cdecl; begin result := '321 test 123'; end; in c++ calling way:
typedef char *testfunc(void); testfunc* function; hinstance hinstlibrary = loadlibrary("test.dll"); if (hinstlibrary) { function = (testfunc*)getprocaddress(hinstlibrary, "test"); if (function) { printf("%s", function()); } } the problem receiving first letter of string. how can tell c++ string not ending after first char?
thanks
you have 2 problems:
- the string delphi sending utf-16 encoded. you'd need encode ansi , return
pansichar, if want match againstchar*. - the memory returned pointer refers liable deallocated when function returns. away in function since return string literal held global constant endures lifetime of dll. string variable, encounter runtime errors when caller tries read memory has been deallocated. confuse matters, runtime errors intermittent. code may appear work. expect failures when deploy important customer!
your options solve item 2:
- arrange caller allocates buffer, can populated callee.
- allocate , deallocate string on shared heap. example com heap
cotaskmemalloc,cotaskmemfree. using shared heap allows allocate in 1 module, , deallocate in other.
as rule of thumb, prefer option 1 if can meet needs.
Comments
Post a Comment