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:

  1. the string delphi sending utf-16 encoded. you'd need encode ansi , return pansichar, if want match against char*.
  2. 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:

  1. arrange caller allocates buffer, can populated callee.
  2. 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

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -