Oh, yes. I missed that
PeekS() does not have
#PB_UTF8 flag. And yes, converting
*curlstring to
Global fixes memory leak. But it will not be threadsafe. You need to make it
Threaded if you have multiple threads calling libcurl:
Code: Select all
Threaded *curlstring
Procedure str2curl(string.s)
If *curlstring <> 0 : FreeMemory(*curlstring) : EndIf
*curlstring=UTF8(string.s)
ProcedureReturn *curlstring
EndProcedure
;example:
curl_easy_setopt(hcurl,#CURLOPT_USERAGENT,str2curl("Mozilla/5.0"))
But memory will be freed only next time you call
str2curl() so this is still not an ideal solution.
This is somewhat better (because it does not need
FreeMemory()) and it is also threadsafe:
Code: Select all
Procedure.s str2curl(string.s)
Protected b=StringByteLength(string.s,#PB_UTF8)
Protected r.s=Space((b+(b%2))/SizeOf(Character))
PokeS(@r.s,string.s,-1,#PB_UTF8)
ProcedureReturn r.s
EndProcedure
Or, do it manually without
str2curl();
Code: Select all
*agent=UTF8("Mozilla/5.0")
curl_easy_setopt(hcurl,#CURLOPT_USERAGENT,*agent)
FreeMemory(*agent)
But it would be best to use
.p-utf8 pseudotype. I see this function inside libcurl.pbi:
Code: Select all
curl_slist_append(slist.i, string.p-utf8)
It is already using
.p-utf8 pseudotype. This is good. But, for example, this next function does not use
.p-utf8:
Code: Select all
curl_easy_setopt(handle.i, option.i, parameter.i)
and from what i understand, 3rd parameter sometimes expects string pointer and sometimes number (depending on 2nd parameter). This can be solved like this:
Code: Select all
ImportC "libcurl.lib"
curl_easy_setopt(handle.i, option.i, parameter.i) ;this is already imported in libcurl.pbi
EndImport
;add these 2 lines to libcurl.pbi after EndImport
PrototypeC Proto_curl_easy_setopt(handle.i, option.i, parameter.p-utf8)
Global curl_easy_setopt_str.Proto_curl_easy_setopt=@curl_easy_setopt()
Now you do not need
str2curl() anymore. Instead of this:
Code: Select all
Protected agent.s = str2curl("Mozilla/5.0")
curl_easy_setopt(hcurl,#CURLOPT_USERAGENT,@agent)
curl_easy_setopt(hcurl,#CURLOPT_TIMEOUT,40)
you can now write this:
Code: Select all
curl_easy_setopt_str(hcurl,#CURLOPT_USERAGENT,"Mozilla/5.0")
curl_easy_setopt(hcurl,#CURLOPT_TIMEOUT,40)
And you do not need to worry about manually freeing memory. Compiler does that under the hood.
If there are some other similar functions that currently also need
str2curl() then you can do the same thing with them as i did now (with
PrototypeC and
Global variable with appended
"_str" or something else).