c++ - How to return a string of unknown size from DLL to Visual Basic -


i have visual basic script calls dll network requests , returns result of 1 request string. length of result unknown before calling dll. dll written in c/c++ myself.

as far see, used way return strings dll pass reference of preallocated string object arguement dll. dll function fills memory returning string. problem allocated buffer has large enough, make sure result fits it.

is possible directly return resulting string dll? or there other way dynamically allocate string object depending on length of result , return vb caller?

i tried different approaches, example (ugly, examples):

__declspec(dllexport) const char* sendcommand(const char* cmd, const char* ipaddress) {     // request stuff...      long lengthofresult = ...     const char* result = new char[lengthofresult];     return result; } 

or like..

__declspec(dllexport) bstr sendcommand(const char* cmd, const char* ipaddress) {     _bstr_t result("test string.");     bstr bstrresult = result.copy();     return bstrresult; } 

the visual basic side:

declare function sendcommand lib "magicdll.dll" (cmd string, ip string) string result = sendcommand("any command", "192.168.1.1") 

both without success - resulting string in vb filled garbage.

most dlls don't return string. accept string param , copy char array buffer. try this:

_declspec(dllexport) int sendcommand(const char* cmd,                                       const char* ipaddress,                                       char* pszbuffer,                                       int nbuffersize) 

and copy string buffer , return number of chars:

int nsize = nbuffersize; if (lstrlen(szmyresult) < nbuffersize)     nsize = lstrlen(szmyresult);  lstrcpyn(pszbuffer, szmyresult, nsize); return nsize; 

when calling vb, allocate string , specify size:

dim s string, intchars long s = space$(128)  intchars = sendcommand("...", "...", s, len(s)) s = left$(s, intchars)  

edit:

if must return string result of function call, can try creating bstr (a vb-style string) , returning that. you'll need convert string unicode , use sysallocstring() create bstr. example:

bstr returnvbstring()  {     return sysallocstring(l"this string c dll."); }  

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -