Quantcast
Channel: Olaf's Thoughts About Development » Android
Viewing all articles
Browse latest Browse all 2

Dealing with MarshalledAString

$
0
0

A couple of versions ago Delphi XE kind of silently introduced the new string types MarshalledString and MarshalledAString.

These types basically map to PChar and PAnsiChar, which worked fine for years. Since Delphi went multi-platform though, there was the need to introduce some stricter abstraction from string types that may exist on all those various platforms, such as Win, MacOSX, iOS and now, with XE5, even Android. And it’s not just platforms, but even a set of different compilers now.

So everytime there are API calls to a certain platform, it’s very likely that you will encounter MarshalledString or MarshalledAString. “Marshalled” means that there needs to be some conversion applied to read or write a “regular” string (which is always Unicode since D2009)

So how would you fill in a “regular string” into this function?

function LOGI(Text: MarshaledAString): Integer;
(A function taken from AnroidAPI.pas)

The important thing here is, that “Text” is MarshalledAString – which means we have to supply an AnsiString. To convert a Delphi Unicode string to Ansi, there is a TMarshaller structure:

var
LMarshaller: TMarshaller;

begin
LOGI(TMarshaller.AsAnsi(‘Hello World’).ToPointer)

AsAnsi does all the dirty work to convert the multibyte Unicode string to a single byte Ansi encoded string (there are overloads to specify a codepage) and returns a TPtrWrapper, which is a structure that points to the actual memory containing the new Ansi string. As MarshalledAString is basically just a pointer, that pointer can easily be supplied using “ToPointer”.


Viewing all articles
Browse latest Browse all 2

Trending Articles