I have a delphi application that uses BTMemoryModule and imports/calls functions from a DLL.
The DLL is written in C/C++.
The delphi application sends an original pwidechar (array of 4 bytes or array of widechars) to a function.
I have no C/C++ pseudo code but it looks like this:
type
TMyFunc = function ( p : pointer ): pointer; stdcall;
procedure anynamehere();
var
Addr : TMyFunc;
MyString : WideString;
begin
[...]
Addr := BTMemoryGetProcAddress('mydll.dll', 'ExportedFunc');
MyString := 'TEST';
[...]
ExportedFunc (pwidechar(MyString));
MessageBoxW (0, pwidechar(MyString), '', 0);
end;
The DLL should now have the original pointer to the MyString var.
The procedure in the delphiapp stays active (until the dll ExportedFunc is finished).
So the MyString var gets NOT disposed after the procedure ends.
My question now is:
Is it possible to CHANGE the value of MyString within the DLL? (technically possible…) But How? The string is null terminated so the user knows how long the pointer length is. But if the C++ DLL changes the value , doesn’t have the user also alloc new space or something? Or does this happen automatically?
Thanks for your help.
The DLL is welcome to change the pointed-to memory if it wants, and it doesn’t need to know the address of
MyString, either. It only needs to know the address stored inMyString, which is exactly what you pass to it already. Since the function receives a pointer to a null-terminated array ofWideCharvalues, the function should be declared like this:It can find out the length of the buffer with
wcslen, and then modify the contents of the buffer in the usual ways. For example:You can have it return some other pointer value if you wish, but since the caller ignores it, it doesn’t really matter in this situation.
When the caller assigned a value to
MyString, space was allocated automatically by the OS on the program’s behalf viaSysAllocString. The caller then passes that buffer to the DLL, and the DLL can modify it. The caller doesn’t need to do anything special with the buffer afterward. Delphi will callSysFreeStringautomatically when the calling function ends andMyStringgoes out of scope.You could also remove the
PWideChartype cast and declare the function to receive aWideStringin Delphi, aBSTRin C++. You could do all the same string manipulations in the DLL in addition to usingSysStringLeninstead ofwcslen. You could passMyStringdirectly to the function: