Return string from a Plug-in (DLL)

I want to return a string (e.g. key) from the DLL function back to the AFL calling the DLL. Since returning strings directly from the DLL function is not possible, I am create a variable in the AFL, and setting its value (string) from the DLL.

In the C++ DLL code, I use the gSite.SetVariable() function as follows :

	AmiVar myVar;
	myVar.type = VAR_STRING;
	myVar.string = "Hello";
	gSite.SetVariable("myMessage", myVar);

In the AFL, I create a string variable (initialized empty), and then call the Test() function of my DLL.
The DLL correctly sets the value to "Hello"

myMessage = "";
testResult = Test(); 
_TRACE("myMessage = " + myMessage);

My question is - is this the correct method ? Can there be any memory leaks ?

Thanks,
Adi.

No it is incorrect. String literals (constants) can NOT be used directly. Any value returned by plugin MUST be allocated using gSite.Alloc (or gSite.AllocArrayResult). There are examples in the ADK documentation.

AmiVar myVar;
myVar.type = VAR_STRING;
const char *string_literal = "Hello";
myVar.string = (char *) gSite.Alloc( strlen( string_literal ) + 1 ); // must use allocated memory since it will be free'd !
strcpy( myVar.string, string_literal );
gSite.SetVariable("myMessage", myVar);
4 Likes

Could you please confirm that after Alloc/AllocArrayResult I do not need to free anything? In the documentation, I saw the following functions but I could not understand if I needed to use them for my plugins:
Init() and Release()

I want to create variables (in an AFL plugin), either for temporary use, or to return back to AFL.

No, you don't need to free memory allocated by AllocArrayResult and returned as result of the function. This memory would be freed by AmIBroker itself (after reference count managed by AB drops to zero).