I will start with a breakdown of what we can see. Keep in mind that we do not have NPPlugin.pas
at hand and you need to infer its contents from the information in the question. However, I think it is possible for us to do this for sure.
s := UTF8Encode(msg);
Here s
is of type string
. This is an alias for UnicodeString
encoded as UTF-16. This way you convert from UTF-16 to UTF-8, and then back to UTF16.
You need it like this:
NPN_SetException(m_pScriptableObject, PAnsiChar(UTF8Encode(msg)));
Alternatively, if you need a variable to store UTF-8 encoded text, declare it UTF8String
, which is equal to AnsiString(65001)
. If you changed type s
to UTF8String
, then the code in the question will be correct. Although somewhat more detailed than it should be.
Another problem here:
OutputDebugStringA(PAnsiChar(Msg + #13#10));
Your order does not make Msg
actually 8-bit encoding. However, you do not want to use the version of the ANSI function. You need it:
OutputDebugString(PChar(Msg + sLineBreak));
Your exception handler is wrong. The task of a DLL is not to rule out leaks. If you try to catch and suppress them, you simply mask the errors in your own code. You need to remove the exception handler and check for errors by following the instructions provided by the library documentation.
Now to the big picture. None of the above explains your reported error. The only sound explanation for this is that your declaration for NPN_SetException
accepts wide text. In this case, you can compile the code simply by writing this:
NPN_SetException(m_pScriptableObject, PChar(msg));
Of course, this makes the appearance of UTF-8 somewhat inexplicable. In fact, the Mozilla library accepts 8-bit text encoded by UTF-8. So, why did NPN_SetException
expect UTF-16 text to be accepted? Well, that is not so. The explanation is that you incorrectly declared NPN_SetException
. So, just to be clear, and PChar(msg)
will make your code compile, this will not solve your problem. You still have code that was not executed at runtime.
So how did this happen? You took the working part of the code that used PChar
aliased to PAnsiChar
on Delphi with PChar
with the alias PWideChar
and not translated correctly. Even when you get the code to compile, it will not work correctly. You started with the code as follows:
function NPN_SetException(..., Msg: PChar): ...;
In older versions of Delphi, where PChar
was PAnsiChar
, that was correct. You are compiling it now on XE7, where PChar
is PWideChar
, and therefore this is not true. It should be:
function NPN_SetException(..., Msg: PAnsiChar): ...;
Then the calling code could be:
NPN_SetException(m_pScriptableObject, PAnsiChar(UTF8Encode(msg)));
My advice is that you:
- Go back and go to Unicode processing in Delphi.
- Go back to the source code and change the Mozilla interface code that uses
PChar
to PAnsiChar
. - Whenever you need to let
PAnsiChar
do this with PAnsiChar(UTF8Encode(str))
.