Marshal::StringToHGlobalAnsi and System.AccessViolationException

D

Dilip

I have cross-posted this question to 3 newsgroups since I am not sure
exactly where it belongs (and some NG's have very less activity).
Apologies in advance for this. I have set the followup to the
dotnet.framework.interop NG but feel free to chage it as appopriate.

I have a question regarding converting a Managed System.String^ to
unmanaged const char*.
I inherited a code that does it like this:

String^ s = "00000";
LPCSTR str = static_cast<LPCTSTR>(const_cast<void*>(static_cast<const
void*>(Marshal::StringToHGlobalAnsi(s))));
char someStr[20];
strncpy_s(someStr, 19, str, 19);
someStr[19] = 0;
Marshal::FreeHGlobal(static_cast<IntPtr>(const_cast<void*>(static_cast<const
void*>(str))));

Leaving aside the fact that there are better ways to accomplish what I
want (like calling .ToPointer() for example) can someone tell me if
that piece of code as it stands has a potential to create problems? I
am getting some System.AccessViolationException around these parts --
although I can't be sure this is what is causing the problem I want to
eliminate it as a potential issue. Here are my issues with that block
of code:

1) It seems to do an unnecessary amount of back-and-forth castings for
what should essentially be cast to a void* and then to a const char*.
First it casts the code to a const void*, then it casts away the const
and then does a cast of const char*. I feel uneasy with so many casts
around.
2) Same with the FreeHGlobal -- too many casts
3) the code that does strncpy seems to be copying more than it
should. I think Marshal::StringTOHGlobalAnsi returns a null-
terminated string. Copying 19 bytes further than seems to be
trampling on memory that doesn't belong to the code.

Any insights?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top