I have a visual basic script that calls to a DLL which does network requests and returns the result of one request as a string. The length of the result is unknown before calling the DLL. The DLL is written in C/C++ by myself.
As far as I see, the most often used way to return strings from a DLL is to pass a reference of a preallocated string object as arguement to the DLL. The DLL function then just fills this memory with the returning string.
The problem is that the allocated buffer has to be large enough, to make sure the result fits into it.
Is it possible to directly return the resulting string from the DLL? Or is there any other way to dynamically allocate a string object depending on the length of the result and return it to a VB caller?
I tried different approaches, for example like this (ugly, just examples):
__declspec(dllexport) const char* sendCommand(const char* cmd, const char* ipAddress)
{
// do 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 as String, ip as String) As String
result = sendCommand("any command", "192.168.1.1")
Both without success - the resulting string in VB is filled with garbage.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…